I have a vuex store, like following:
import spreeApi from \'../../gateways/spree-api\'
// initial state
const state = {
products: [],
categories: []
}
// mu
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)
}
And if I have some common code that affects state between multiple mutations, I have to duplicate the same code on all my mutations? Or there's a better way to do that?
First, assign the Vue button to a variable: In main.js:
export const app = new Vue({
router,
vuetify,
store,....
Then import the "app" variable to the js file where you define the mutation: In modules.js:
import { app } from "../../main";
You can now use it as "app.$store.commit":
mutations: {
[AUTH_SET_TOKEN]: () => {
app.$store.commit(USER_SUCCESS, params );
},...
i think
calling mutation from another mutation is bad idea because of hard to debug state and components
const mutations = {
mutationOne(state, payload){
this.commit("mutationTwo", payload)
},
mutationTwo(state, payload){
console.log("called from another mutation", payload)
}
}
but you can write simple function and function can reusable
function mysecondfn(state,payload){
{
// do your stuff here
}
const mutations = {
mutationOne(state, payload){
mysecondfn(state,payload)
},
}
Reading the Vuex documentation on Actions, it's quite clear what they are made for.
Actions can (not must) contain asynchronous code. In fact, the following example is correct
increment (context) {
context.commit('increment')
}
I do not see any issue in using actions for performing multiple mutations.
import spreeApi from '../../gateways/spree-api'
// initial state
const state = {
products: [],
categories: []
}
// mutations
const mutations = {
SET_PRODUCTS: (state, {response,commit}) => { // here you destructure the object passed to the mutation to get the response and also the commit function
state.products = response.data.products
commit('SET_CATEGORIES') // now the commit function is available
},
SET_CATEGORIES: (state) => {
state.categories = state.products.map(function(product) { return product.category})
}
}
const actions = {
FETCH_PRODUCTS: ({commit}, filters) => { // here you destructure the state to get the commit function
return spreeApi.get('products').then(response => commit('SET_PRODUCTS', {response,commit})) // here you pass the commit function through an object to 'SET_PRODUCTS' mutation
}
}
export default {
state,
mutations,
actions
}
This should fix it. You can inject the commit into your mutation from the action so you can commit from your mutation. Hope this helps