In the documentation, it is written that the state is immutable apart from the mutations called via the actions … Ok.
I use in my component, mapGetters, mapActions …
store :
export default {
namespaced: true,
state: {
color: "violet"
},
mutations: {
changeColor(state, newColor) {
state.color = newColor
},
},
actions: {
changeColor({ commit }, newColor) {
commit('changeColor', newColor)
}
}
component :
...
methods: {
...mapActions({
setColor: 'store/changeColor',
}),
myMethodCallByButton(){
this.setColor("blue").then(response => {
console.log("change Color done")
},err => {
console.log("change Color error")
})
}
...
The method works fine, the store is updated, EXCEPT that I never receive the console.log ().
It is written in the documentation that mapActions were equivalent to this.$store.dispatch.
- Why do not I get the message?
- Is there another solution ?
PS: I want to keep the mapGetters map, mapActions .. I do not like calling this.$store.dispatch
PS2: I work with modules in my store
Thank you
Best Answer
Every Vuex action returns a
Promise
.Vuex wraps the results of the action functions into
Promise
s. So thechangeColor
action in:Returns a
Promise
that resolves toundefined
and that will not wait for the completionmyAsyncCommand();
's asynchronous code (if it doesn't contain async code, then there's no waiting to do).This happens because the code above is the same as:
And when
.dispatch('changeColor', ...)
Vuex will then returnPromise.resolve(undefined)
.If you want the
Promise
returned by the action to wait, you should return aPromise
that does the propert waiting yourself. Something along the lines of:Demo implementation below with more details:
Update/Per comments:
If an action calls a mutation only, such as:
Then the returned
Promise
will only execute after thecommit()
completes.That does not happen because Vuex manages waiting of mutations (
commit
s).It happens that way because there's no waiting to do. This is because Vuex requires: mutations must be synchronous operations.
Since mutations are synchronous, the line of the
return
above will only execute after the code of the line before (commit('changeColor', newColor)
).Note: If your mutations have asynchronous code, you should make them synchronous, as it goes against how Vuex properly works and may yield all kinds of unexpected behaviors.