Search code examples
javascriptvuexvuex-modules

How use a mutation function in a action function in Vuex?


I have this Vuex:

export default new Vuex.Store({
  state: {
    userInfo: {
      nit_ID: { ID: '', Desc: '' },
      userName: { ID: '', Desc: '' },
      typeDocument: { ID: '', Desc: '' },
      document: '',
    },    
    globalPublicKey: 'ASDFGHJKL1234567890',
  },
  mutations: {    
    updateUserInfo(state, payload) {
      state.userInfo = payload;
    }, 
  },
  getters: {
    userInfo: (state) => { return state.userInfo; },
  },
  actions: {
    validateUserSession(context) {
      var valido = false;
      try {       
        let storageInfo = JSON.parse(
          sjcl.decrypt(context.state.globalPublicKey, localStorage.userInfo)
        );
        if (localStorage.userToken === storageInfo.token) {
          context.mutations.updateUserInfo(storageInfo);          
          valido = true;
        }
      } catch (e) {
          console.error(e);
      }
      return valido;
    },
  },
})

But the problem is that I can't access to the mutation updateUserInfo(), I know that is easy to solved, only do the updateUserInfo process in my action, but the question is How can I use a mutation into a action?


Solution

  • In VueJS you can call a mutation from an action by calling context.commit, like this:

    context.commit('mutationName', params)

    params can be omitted if not parameters are passed to the mutation.

    More on this here: vuex.vuejs.org/guide/actions.html

    Actually you call a mutation from anywhere with a commit - but it's advised to use actions (so dispatch an action) that in turn commits the data (actually mutates the state).