Search code examples
vuejs2vuex

Vuex state update is not updating DOM


I have an array of objects in state

  hostInstances :  []

And an computed property

getHostInstances(){
  return this.$store.state.hostInstances
}

which initially show exact number of objects but if I push new object state change is showed in vuedev tools but computed property doesn't change.

I even tried getter via computed property

  ...mapGetters(['getHostInstances' ]);

and directly in dom

v-for="instance in $store.getters.getHostInstances"

but it doesn't updated the dom.


Solution

  • You don't need getters as you don't transform your state. You can just fetch it directly from the store using mapState of Vuex. You must also modify the state through mutations only if you're not using one.

    import { mapState } from 'vuex';
    
    ...
    computed: {
       ...mapState(['hostInstances'])
    },
    methods: {
      addHostInstance() {
        this.$store.dispatch('addHostInstanceAction', yourHostInstanceObj);
      }
    }
    

    and in your store...

    export default new Vuex.Store({
      state: {...}
      actions: {
        addHostInstanceAction({commit}, payload) {
          commit('mutateInstances', payload);
        }
      },
      mutations: {
        mutateInstances(state, payload) {
          state.hostInstances.push(payload);
        }
      }
    })