Sometimes, we want to use async and await with Vuex dispatch.
In this article, we’ll look at how to use async and await with Vuex dispatch.
How to use async and await with Vuex dispatch?
To use async and await with Vuex dispatch, we can add an action method that’s an async function.
For instance, we write
const store = new Vuex.Store({
//...
actions: {
getProducts: async ({ commit }, type) => {
try {
const { data: products } = await axios.get(`/api/products/${type}`);
commit("SET_PRODUCTS", { products, type });
} catch (err) {
console.log(err);
}
},
},
//...
});
to add the getProducts
action that makes an async request with axios.get
.
And then we call commit
to commit the SET_PRODUCTS
mutation to store the data.
Conclusion
To use async and await with Vuex dispatch, we can add an action method that’s an async function.