Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vuex actions that do not need to commit a mutation

Tags:

vue.js

vuex

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?

like image 724
Ron Chan Avatar asked Oct 03 '18 15:10

Ron Chan


People also ask

What is the difference between actions and mutations Vuex?

Actions are similar to mutations, the differences being that: Instead of mutating the state, actions commit mutations. Actions can contain arbitrary asynchronous operations.

Can I call action from mutation Vuex?

In Vuex, actions are functions that call mutations. Actions exist because mutations must be synchronous, whereas actions can be asynchronous. You can define actions by passing a POJO as the actions property to the Vuex store constructor as shown below. To "call" an action, you should use the Store#dispatch() function.

Can Vuex actions be async?

An action in Vuex is where you perform interaction with APIs and commit mutations. Such interactions are inherently asynchronous.

What is strict mode in Vuex?

Strict mode runs a synchronous deep watcher on the state tree for detecting inappropriate mutations, and it can be quite expensive when you make large amount of mutations to the state. Make sure to turn it off in production to avoid the performance cost.


2 Answers

you can use _ instead of {commit}

getAllUser(_, payload) {
    let response = await ApiService.getAllUser(
        payload.params
    );
    return response;
}
like image 153
Nayeem Ahmed Avatar answered Nov 07 '22 01:11

Nayeem Ahmed


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.

like image 31
van-koelljor Avatar answered Nov 07 '22 02:11

van-koelljor