Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call commit from one of mutations in Vuex store

I have a vuex store, like following:

import spreeApi from '../../gateways/spree-api' // initial state const state = {   products: [],   categories: [] }  // mutations const mutations = {  SET_PRODUCTS: (state, response) => {    state.products = response.data.products    commit('SET_CATEGORIES')  },  SET_CATEGORIES: (state) => {    state.categories = state.products.map(function(product) { return product.category})  }  }  const actions = {  FETCH_PRODUCTS: (state, filters) => {    return spreeApi.get('products').then(response => state.commit('SET_PRODUCTS', response))  } }  export default {   state,   mutations,   actions } 

I want to call mutation: SET_CATEGORIES from mutation: SET_PRODUCTS, But this gives me error:

projectFilter.js:22 Uncaught (in promise) ReferenceError: commit is not defined(…)

What should be correct way to do this. I tried store.commit and this.commit, but these also gave similar errors.

like image 917
Saurabh Avatar asked Nov 08 '16 13:11

Saurabh


People also ask

Can I call action from mutation Vuex?

In Vuex, actions are functions that call mutations. Actions exist because mutations must be synchronous, whereas actions can be asynchronous. You can define actions by passing a POJO as the actions property to the Vuex store constructor as shown below. To "call" an action, you should use the Store#dispatch() function.

How do you commit a mutation from another module Vuex?

To change another module state from one module in Vuex, we can call commit with the mutation name with the root option set to true . commit("TOGGLE_LOADING", null, { root: true }); to call commit to commit the TOGGLE_LOADING mutation with root set to true .

How do I dispatch action from mutation Vuex?

Mutations can't dispatch further actions, but actions can dispatch other actions. So one option is to have an action commit the mutation then trigger the filter action. Another option, if possible, would be to have all filters be getters that just naturally react to data changes like a computed property would.

How do you access getters in mutations Vuex?

To access getters within Vuex mutations with Vue. js, we just use the state in the getter and call the getter with the state . //... const store = new Vuex.


1 Answers

If you absolutely must commit two mutations, why not do it from an action? Actions don't have to perform async operations. You can destructure the commit method in your action the same way you do with state like so:

commitTwoThings: ({commit}, payload) => {   commit('MUTATION_1', payload.thing)   commit('MUTATION_2', payload.otherThing) } 
like image 91
Daniel S. Deboer Avatar answered Oct 16 '22 14:10

Daniel S. Deboer