T
T
tripcollor2018-12-24 18:47:21
JavaScript
tripcollor, 2018-12-24 18:47:21

Why in nuxt in a variable inside state the value is not read from the cookie gives out undefined?

I do authorization when accessing api, I get a token from I write it to $store.state.token It is
necessary to write this token to Cookie and when loading the page, take the value of the token from Cookie or set it to null if it does not exist.
In the shared state object, I define a variable equal to token: Cookies.get('accessToken') || null
Call Cookies.get('accessToken') in this case, we issue undefined
Above the definition of the store constant, I turned to Cookie and wrote it to the globalToken variable, which I later displayed in the console, everything is fine there and the console issues a token, but when I assign this variable in store.state.token = globalToken , then it's undefined again
How can I solve this problem?

import Vue from 'vue'
import Vuex from 'vuex'
import Cookies from 'js-cookie';

Vue.use(Vuex)

let globalToken = Cookies.get('accessToken')
console.log('globalToken', globalToken)

const store = () => new Vuex.Store({
  state: {
    token: Cookies.get('accessToken') || null,
  },
  mutations: {
    retriveToken(state, token){
      state.token = token
    },
  },
  actions: {
    retriveToken(context, credentials){
      this.$axios.post('/login', {
        username: credentials.username,
        password: credentials.password
      })
      .then(function (response) {
        const token = response.data.access_token;

        Cookies.set('accessToken', token)
        context.commit('retriveToken', token)
      })
    }
  },
})

export default store

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2018-12-24
@alekstar79

That is, when you start the application, exactly with this code, you have a token displayed in the console, and undefined in the state? Or like... Where do you look in the store that Cookies.get('accessToken') === undefined. Or where do you have the assignment of globalToken in the store? And when you have an action called? Perhaps it hangs on a hook... And what comes from the server? Without seeing the logic as a whole, it’s hard to say why you have it somewhere, it’s not clear where, undefined.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question