[Vuejs]-VueJS – Vuex Assign data in a mutation

4πŸ‘

βœ…

In the store u can load ur data asynchronously via actions then commit the changes using a mutation.

import vue from 'vue';
import Vuex from 'vuex';

vue.use(Vuex);

export default new Vuex.Store({
  state: {
    users: {
      columns: [],
      model:   [],
    }
  },

  actions: {
    fetchUsers: function( context ) {
      axios.get(`/users?search_input=`)
      .then( function( response ) {
        context.commit( "FETCHUSERS", {
          columns: response.columns,
          model: response.model
        });  
      });   
    }
  }
  mutations: {
    FETCHUSERS: function( state, payload ) {
      state.users.columns = payload.columns;
      state.users.model = payload.model;
    }
  }
});

Dispatch the action from the component

<script>
  export default {
    .....
    methods: {
      fetchUsers: function() {
       this.$store.dispatch( "fetchUsers" );
      }
    }
  }
</script>
πŸ‘€Tarik Chakur

1πŸ‘

Mutations must be synchronous: https://vuex.vuejs.org/en/mutations.html

You should move ajax request into actions, which can be async. You get data in the action, commit mutation giving received data as a payload, and mutation assigns a value to the state property.

Alternatively, you can make async request in component method, and assign a value to the store property directly: this.$store.state.prop = value

Leave a comment