How to handle asynchronous operations in Vuex actions?

Vuex actions are often used for asynchronous operations. They receive a context object that includes a commit method to trigger mutations.

// store.js
export default new Vuex.Store({
  state: {
    data: null
  },
  mutations: {
    setData(state, payload) {
      state.data = payload;
    }
  },
  actions: {
    fetchData({ commit }) {
      // Simulating an async API call
      setTimeout(() => {
        const result = 'Fetched data from the server';
        commit('setData', result);
      }, 1000);
    }
  }
});

To dispatch the action in a component:

// MyComponent.vue
export default {
  methods: {
    fetchData() {
      this.$store.dispatch('fetchData');
    }
  }
};

 

Post your Answer