Search code examples
vuexvuex-modules

How acccess mutation from one store file for another store file?


How can I access a mutation from one file in my store folder that exists in another file in my store folder?

Here's my directory:

store/
     user.js
     loading.js

In user.js I have:

  async googleSignInRedirect({ commit }) {
    try {
      const result = await this.$fire.auth.getRedirectResult()
      if (result.credential) {
        // const credential = result.credential
        // console.log('got a credential? ', credential)
        this.$router.replace('/')
        commit('loading/SET_LOADING', false) //< -- what is correct way to write this ?
      }
      return null
    } catch (error) {
      console.error(error)
    }
  },

Here is the loading.js code:

export const state = () => ({
  loading: false
})

export const mutations = {
  SET_LOADING(state, payload) {
    state.loading = payload
  }
}

How can I access loading.js from user.js ? If I do the above style, I get the following error in console:

vuex.esm.js?2f62:791 [vuex] unknown local mutation type: loading/SET_LOADING, global type: user/loading/SET_LOADING

Solution

  • Just pass { root: true } as the final argument to commit, so:

      async googleSignInRedirect({ commit }) {
        try {
          const result = await this.$fire.auth.getRedirectResult()
          if (result.credential) {
            this.$router.replace('/')
            commit('loading/SET_LOADING', false, { root: true })
          }
          return null
        } catch (error) {
          console.error(error)
        }
      }
    

    You can find more details in the Vuex documentation.