Can I call commit from one of mutations in Vuex store

Can I call commit from one of mutations in Vuex store

Asked on January 8, 2019 in vue.js.
Add Comment


  • 2 Answer(s)

           By using mutation, there is no way to commit another mutation. A mutation is a synchronous call which changes the state. Within one mutation, It is not able to commit another mutation.

           vuex reference: https://vuex.vuejs.org/en/api.html

           As you can see, a mutation handler receives only state and payload. Therefore getting commit as undefined.

          Incase to set the PRODUCT and CATEGORIES as part of the similiar mutation handler as a single commit.

    // mutations
          const mutations = {
              SET_PRODUCTS_AND_CATEGORIES: (state, response) => {
                  state.products = response.data.products
                  state.categories = state.products.map(function(product) { return product.category})
    },
    // ...
    }
    
    Answered on January 8, 2019.
    Add Comment

           It should commit two mutations, Incase Actions don’t have to perform async operations. It is able to destructure the commit method action the same way to do so:

    commitTwoThings: ({commit}, payload) => {
         commit('MUTATION_1', payload.thing)
         commit('MUTATION_2', payload.otherThing)
    }
    
    Answered on January 8, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.