Search code examples
vue.jsinitializationvuex

How i can run mutation during creation Vuex.Store object or define the initial value?


I have an array. I take data for it via rest api. I can call a mutation getData() from any component, but I need it to be automatically called when an object Vuex.Store is created, can I do this?

export default new Vuex.Store({

state: {
    myArray: [],       
},

 mutations: {

    getData() {
       
       //get data from remote API and pass to myArray
       axios.post('').then(response => {
             this.myArray = response.data;
       };
    }
  }
 })

Solution

  • First things first: Mutations are synchronous pure functions. This means that your mutations should not have side-effects, and at the end of your mutation the state of your store should be updated to the new state. Axios uses promises and is thus asynchronous. You should do this in an action!

    As for automatically executing a data fetch, you can either do this in the file where you define your store, or in your Vue entry point (e.g. App.vue) in a lifecycle hook. Keep in mind though that your axios call is asynchronous, which means that your app will load while data is loading in the background. You have to handle this case somehow.

    // store.js
    import Vue from 'vue';
    import Vuex from 'vuex';
    
    const store = new Vuex.Store({
      state: {
        myArray: [],
      },
      mutations: {
        setMyArray(state, payload) {
          Vue.set(state, 'myArray', payload);
        },
      },
      actions: {
        fetchData({ commit }) {
          axios.post('').then(response => {
            commit('setMyArray', response.data);
          };
        }
      }
    });
    
    // Setup
    Vue.use(Vuex);
    
    // Now that we have a store, we can literally just call actions like we normally would within Vue
    store.dispatch('fetchData');
    
    // Keep in mind that action is not blocking execution. Execution will continue while data is fetching in the background