What is Action in Vuex: Explanation and Example
action is a function that handles asynchronous tasks or complex logic before committing mutations to change the state. Actions let you perform operations like API calls and then commit mutations to update the store.How It Works
Think of Vuex actions as helpers that do the hard work behind the scenes before updating your app's state. Unlike mutations, which must be synchronous and directly change the state, actions can run asynchronous code like fetching data from a server.
When you dispatch an action, it can perform tasks such as waiting for a response or processing data, then it commits a mutation to update the state. This separation keeps your state changes predictable and easier to track.
Imagine you want to bake a cake (update state). Mutations are like the final step of putting the cake in the oven, while actions are like mixing ingredients and preparing the batter first.
Example
This example shows a Vuex action that fetches user data asynchronously and commits a mutation to save it in the state.
import { createStore } from 'vuex'; const store = createStore({ state() { return { user: null }; }, mutations: { setUser(state, userData) { state.user = userData; } }, actions: { async fetchUser({ commit }) { // Simulate API call with a delay const userData = await new Promise(resolve => { setTimeout(() => { resolve({ id: 1, name: 'Alice' }); }, 1000); }); commit('setUser', userData); } } }); // Usage example store.dispatch('fetchUser').then(() => { console.log(store.state.user); });
When to Use
Use actions in Vuex when you need to perform asynchronous operations before changing the state. Common cases include fetching data from APIs, waiting for timers, or handling complex logic that shouldn't be inside mutations.
For example, if your app needs to load user info from a server, you would dispatch an action to get the data, then commit a mutation to update the store once the data arrives.
Actions help keep your state changes clean and make your app easier to debug and maintain.
Key Points
- Actions can be asynchronous, mutations cannot.
- Actions commit mutations to update the state.
- Use actions for API calls and complex logic.
- Dispatch actions with
store.dispatch('actionName'). - Keep mutations simple and synchronous for predictable state changes.