How to define actions in Vuex
Vuex actions handle asynchronous operations and complex business logic before committing mutations to change application state in Vue applications. With over 25 years of experience building complex applications and as the creator of CoreUI, I use Vuex actions extensively for API calls and async operations. The most effective approach is defining actions as functions that receive a context object with commit, dispatch, and state properties. This provides a clean separation between async operations and state mutations while maintaining predictable data flow.
Define Vuex actions as functions that handle asynchronous operations and commit mutations to update application state.
// store/index.js
import { createStore } from 'vuex'
import api from '@/services/api'
const store = createStore({
state: {
users: [],
loading: false,
error: null
},
mutations: {
SET_LOADING(state, isLoading) {
state.loading = isLoading
},
SET_USERS(state, users) {
state.users = users
},
SET_ERROR(state, error) {
state.error = error
}
},
actions: {
// Simple async action
async fetchUsers({ commit }) {
commit('SET_LOADING', true)
try {
const users = await api.getUsers()
commit('SET_USERS', users)
commit('SET_ERROR', null)
} catch (error) {
commit('SET_ERROR', error.message)
} finally {
commit('SET_LOADING', false)
}
},
// Action with payload
async createUser({ commit, dispatch }, userData) {
try {
const newUser = await api.createUser(userData)
commit('ADD_USER', newUser)
// Dispatch another action
await dispatch('fetchUsers')
return newUser
} catch (error) {
commit('SET_ERROR', error.message)
throw error
}
},
// Action accessing state
async updateUser({ commit, state }, { id, updates }) {
const user = state.users.find(u => u.id === id)
if (!user) return
try {
const updatedUser = await api.updateUser(id, updates)
commit('UPDATE_USER', updatedUser)
} catch (error) {
commit('SET_ERROR', error.message)
}
}
}
})
Actions receive a context object with commit for mutations, dispatch for other actions, and state for accessing current state. They handle async operations like API calls, perform error handling, and commit mutations to update state. Actions can dispatch other actions and return promises for component handling.
Best Practice Note:
This action pattern is used throughout CoreUI’s Vue applications for reliable async state management. Always handle errors in actions and use try-catch blocks to maintain application stability while providing meaningful error feedback to users.



