Vue.js – vuex actions that do not need to commit a mutation

vue.jsvuex

Using Vue and Vuex, I have followed the recommended practice of making changes to state only via mutations. So all Vue components will make changes to state via the use of an action which then in turn commits a mutation. I also make API calls in some actions which then update state based on the result.

I now have some API calls that do not need the state to be updated after they are called. Question is should I still use actions? or should I bypass vuex and make those calls directly from components?

Best Answer

The main reasons for using actions are these:

  • mutations have to be synchronous, actions can be asynchronous -> If you want to deal with asynchronous operations before a mutation, you have to use an action
  • if you want to commit multiple mutations at once, you can bundle them logically into one action

So in conclusion, you are right: If it is clear to you that these API calls do not alter the application's state in any way, they shouldn't be called by using actions.

Make those calls directly inside your components, import a module holding the needed functions or put the respective methods into a mixin if you want them to be shared between multiple components.

If you should, however, find out during development that the result of these calls should be shared between multiple components of your application, move the respective logic to the store via actions and mutations.

Related Topic