Search code examples
javascriptvue.jstokenvuexvuex-modules

How to access a Vuex base state from a module


I successfully made a group in Vuex, but how do I access from the group to the base/non group state? In this case I want to access a user token from state in the base/non group state from product group.

This is my product group

const product = {
  state: () => ({
    product: [

    ]
  }),
  mutations: {
    retreiveProduct(state,product){
      state.product = product
    },
  },
  actions: {
    retreiveProduct(context){
      axios.defaults.headers.common['Authorization'] = 'Bearer ' + context.state.token
      axios.get('/products')
        .then(response=>{
          context.commit('retreiveProduct',response.data)
        })
        .catch(error => {console.log(error)})
    },
  },
  getters: {

  }
}

There is an error when getting the token from "context.state.token" in code above

and this is my user token code

export const store = new Vuex.Store({
  modules: {
    product
  },
  state:{
    token: localStorage.getItem('access_token') || null,
    filter: 'all',
  },
})

If u see, I have declared a variable token and filled it with access_token. Can I call this variable from product group, or do I have to create another token variable in product group ?

Or do I have to make the other group retain the token ?

Can this be solved by namespace?


Solution

  • Since the action is in a Vuex module, and the state you're accessing is in the Vuex store root instead of the module's state, you need to access rootState from the context object instead of state:

    axios.defaults.headers.common['Authorization'] = 'Bearer ' + context.rootState.token
    

    The context object has:

    • state
    • rootState
    • getters
    • rootGetters
    • commit
    • dispatch