Is it good practice to use Vuex store actions to perform related asynchronous operations (e.g., GET requests) without actually modifying the state of the store?
I have a Vuex store. Let's call it Host.
It contains an object as its state, with some getters to retrieve various forms of the state as well as some mutations to modify said state.
However, when it comes to actions, I perform certain asynchronous requests on host objects which I pass in to the actions as a parameter. For instance, a Host can be enabled or disabled.
I, therefore, have an action hostEnable(host)
, which calls an Axios GET request which responds only with an OK (200).
const getDefaultState = () => {
return {
host: {...}
}
};
export const state = getDefaultState();
const getters = {
getHost: (state) => {
return state.host;
},
...
};
const mutations = {
setHost: (state, host) => {
state.host = host;
},
...
};
const actions = {
fetchHost ({commit}, hostId) => {
api.get(hostId)
.then(({data}) => {
commit(setHost, data);
})
.catch(error => {
throw new Error(error);
});
},
createHost: ({state}) => {
return api.create(state.host);
},
hostEnable: (context, host) => {
return api.enableHost(host);
},
...
};
export default {
state,
getters,
actions,
mutations
};
Is it fine to use a Vuex store in this way, or do all actions have to either use or modify the store state?
Is it fine to use a Vuex store in this way, or do all actions have to either use or modify the store state?
In this scenario, yes, it's perfectly fine and no, it doesn't have to modify anything.
Even though, it's not gonna behave in the way that a Vuex action is intended to work (since technically, actions are supposed to work with mutations in some fashion), you can define hostEnable
as an action because it makes more sense to group all Host
related business logic in one single module rather than putting it somewhere else in your codebase.
So yeah, you can use it to perform asynchronous operations without committing any mutations to your store data since it's also responsible for containing complicated business logic in your application.
Lastly, using actions
for asynchronous logic is one of the high-level principles when structuring your Vue application.
Application-level state is centralized in the store.
The only way to mutate the state is by committing mutations, which are synchronous transactions.
Asynchronous logic should be encapsulated in, and can be composed with actions.
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