How to update an entire array with Vuex?

Sometimes, we want to update an entire array with Vuex.

In this article, we’ll look at how to update an entire array with Vuex.

How to update an entire array with Vuex?

To update an entire array with Vuex, we can use the Vue.set method.

For instance, we write

import Vuex from "vuex";
const store = new Vuex.Store({
  state: {
    items: [],
  },
  mutations: {
    MUTATE_ITEMS: (state, items) => {
      Vue.set(state, "items", [...items]);
    },
  },
  actions: {
    loadItems: (context, items) => {
      context.commit("MUTATE_ITEMS", items);
    },
  },
});

to add the MUTATE_ITEMS mutation method that calls Vue.set with state, the property in state to update, and the new value for state.items.

Using Vue.set will trigger reactivity in Vue, so all the components that listens for the store state will re-render if the values it’s watching have changed.

Conclusion

To update an entire array with Vuex, we can use the Vue.set method.