Categories
Vue Answers

How to fix pushing to Vuex store array not working in Vue.js?

Spread the love

Sometimes, we want to fix pushing to Vuex store array not working in Vue.js.

In this article, we’ll look at how to fix pushing to Vuex store array not working in Vue.js.

How to fix pushing to Vuex store array not working in Vue.js?

To fix pushing to Vuex store array not working in Vue.js, we should commit the mutation to change the array state.

For instance, we write

const store = new Vuex.Store({
  state: {
    customers: [{ id: 1, name: "user 1" }],
  },
  mutations: {
    addCustomer(state, customer) {
      state.customers.push(customer);
    },
  },
});

to add the addCustomer mutation that calls state.customers.push to add an entry to the customers state.

And then in our component, we write

<script>
//...
export default {
  //...
  methods: {
    addCustomer() {
      store.commit("addCustomer", { id: 2, name: "User 2" });
    },
  },
  //...
};
</script>

to call store.commit with 'addCustomer' and the item to add to commit the addCustomer mutation.

Conclusion

To fix pushing to Vuex store array not working in Vue.js, we should commit the mutation to change the array state.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *