Vuex: Call getters from action

The Bassman picture The Bassman · Aug 28, 2018 · Viewed 45.3k times · Source

Is there a way for a dispatch/action to call a getter inside of it?

mutations: {
    setData(state, data) {
        state.data = data;
    }
}
actions: {
    sendDataToServer({ commit }, payload) {
        // call getter (data) and assign to variable
        // do async functions from the data returned
    }
},
getters: {
    getAppData: state => () => {
        return state.data;
    }
}

So what's the best practice here? Using the mutation to change the state and then get the state and pass it to action which will then execute the async function or do I need to restructure my implementation?

call mutation -> get the data via getter -> call action

OR

do it all on the action (do mutation on the action and do the action/async method without the need of the getter)?

Answer

Tugay İlik picture Tugay İlik · May 2, 2019

In addition to commit, actions has default injected parameters which are dispatch, getters and rootGetters. So you can simply write;

sendDataToServer({ commit, getters }, payload) to access getters.