Open In App

Action vs Mutations in Vuex

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The Vuex is a state management library designed specifically for the Vue.js applications. It helps manage shared state in a centralized store, making it easier to handle complex applications. In Vuex, actions and mutations are crucial concepts for managing state changes. we will going to discuss both of them.

These are the following topics that we are going to discuss:

What is an Action in Vuex?

An action in Vuex is a method used to handle asynchronous operations and commit mutations to change the state. The Actions can contain any arbitrary asynchronous operations such as the API calls which makes them ideal for managing complex state changes that depend on the external data. Actions can be dispatched from the components to trigger state changes indirectly through the mutations.

Example: Here is an example of a Vuex action that fetches user data from the API and commits the data to the state.

JavaScript
// App.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    user: null,
  },
  mutations: {
    SET_USER(state, user) {
      state.user = user;
    },
  },
  actions: {
    async fetchUser({ commit }) {
      try {
        const response = await fetch('https://api.example.com/user');
        const data = await response.json();
        commit('SET_USER', data);
      } catch (error) {
        console.error('Error fetching user:', error);
      }
    },
  },
});

Output: Here's a sample console output if the API call is successful:

{
  id: 1,
  name: "John Doe",
  email: "[email protected]"
}

What is a Mutation in Vuex?

A mutation in Vuex is a synchronous method that directly modifies the state. The Mutations are the only way to change the state in the Vuex store. They are essential for the tracking state changes in applications and should be simple functions that take the current state and a payload as the arguments.

Example: Here is an example of a mutation that updates the user's information in the state:

JavaScript
mutations: {
  SET_USER(state, user) {
    state.user = user;
  },
  UPDATE_USER(state, updatedInfo) {
    Object.assign(state.user, updatedInfo);
  },
},

Output:

state.user = {
  name: 'Jane Smith',
  email: '[email protected]',
  age: 26,
};

Difference Between Actions and Mutations

Characteristics

Actions

Mutations

Purpose

Handle asynchronous operations and commit mutations

Directly modify the state

Invocation

Triggered by dispatching actions

Called directly in Vuex store

Async Support

The Supports asynchronous operations

The Must be synchronous

Context

Has access to the store context and can perform API calls

Has access only to the state

Call Syntax

store.dispatch('actionName')

store.commit('mutationName')

Conclusion

In Vuex, actions and mutations play distinct but complementary roles in managing state. Actions are used for handling asynchronous operations, while mutations are responsible for directly modifying the state. Understanding the differences between these two concepts is essential for effectively managing state in Vuex-powered applications.


Next Article
Article Tags :

Similar Reads