[Vuejs]-Vuex update view on commit

2👍

Your problem is that mutations are synchronous, while you’re making an axios.get call inside your mutation (which is asynchronous).

You should handle the axios.get either in your component or in a vuex action:

Using a vuex action to handle the axios.get() call:

export const store = new Vuex.Store({
  state: {
    pacientes: []
  },
  mutations: {
    setPacientes(state, payload) {
      // note how we don't call this.state.
      // state comes as param.
      state.pacientes = payload.pacientes;
    },
  actions: {
    fetchPacientes(context){
      axios.get('http://slimapi/api/pacientes')
      .then(response => {
          context.commit('setPacientes', {pacientes: response.data});
      })
      .catch(e => {
          console.log(e)
      }) 
    }
  }
  }
});

And then in your component:

agregarTurno() {
  // commit is for mutations, while dispatch is for actions
  this.$store.dispatch('fetchPacientes')
}

avoiding vuex action:

You could make the api call in your component, and then just commit the mutation:

agregarTurno() {
  axios.get('http://slimapi/api/pacientes')
  .then(response => {
    this.$store.commit('setPacientes', {pacientes: response.data});
  })
  .catch(e => {
      console.log(e)
  })
}

However, if several components will make this api call, you can avoid code duplication by placing it in a vuex action.

I think that placing that kind of async code in the store as a vuex action is generally considered a best practice.

Some issues in your pasted code

You don’t need to dispatch an action both in created() and mounted() hooks. I guess created() is the best option.

To make your component react to the store, setup a data() member that refers to the pacientes in the store is ok, I would do:

data () {
  return {
    pacientes: this.$store.state.pacientes
    }
  },

Now, if your component would use a lot of things of the store, I would setup a vuex getter.

Leave a comment