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?
Actions are similar to mutations, the differences being that: Instead of mutating the state, actions commit mutations. Actions can contain arbitrary asynchronous operations.
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.
An action in Vuex is where you perform interaction with APIs and commit mutations. Such interactions are inherently asynchronous.
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.
you can use _ instead of {commit}
getAllUser(_, payload) {
let response = await ApiService.getAllUser(
payload.params
);
return response;
}
The main reasons for using actions are these:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With