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.
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.
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 .
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.
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.
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With