Vuex: Skipping Action and committing Mutation directly from Component

Javascriptvue.jsVuejs2Vue ComponentVuex

Javascript Problem Overview


In vue.js app, using vuex as state management store, I need to simply change the value of a property in vuex. For this I can follow two methods:

  1. Dispatch an action method, which will further commit mutation, which eventually will change the state.

  2. The second method is to commit the mutation directly from the component and the mutation method will then change the state.

Currently, I'm using first method like this:

In Component:

this.$store.dispatch('updateNotice', 'This is some notice')

In Actions:

updateNotice ({state, getters, commit}, payload) { commit('UPDATE_NOTICE', payload) }

In Mutations:

UPDATE_NOTICE (state, payload) { state.notice = payload }

As you might have noticed, I'm using the action method simply to commit a single mutation, without any other logic or async functionality.

My question is, in this case, should I not directly commit the mutation from the component itself? What is the best practice? Since using action method in this simple case seems verbose and serve no specific purpose.

Is there any reason that I should always commit actions from a component? Afterall, in vuex the ...mapMutations() have some reason to exist.

Javascript Solutions


Solution 1 - Javascript

In your case it should be fine to commit the mutations directly in your components using ...mapMutations or $store instance.

Since you asked the best practice, The primary reason for the existence of Actions is Asynchronicity. Mutations cannot be asynchronous whereas Actions can be, while you can call $store.commit directly in a Component this will be a synchronous event, but when you call dispatch the commit can be handled asynchronously within the action block unlike Mutations.

So the best practice is to use Actions to commit modifications to your state when it has to be handled asynchronously say you need to do an API call before committing the state change in such cases it would be a good idea to use Actions.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFaisal KhurshidView Question on Stackoverflow
Solution 1 - JavascriptVishnu NairView Answer on Stackoverflow