Categories
JavaScript Answers

How to fix push to Vuex store array not working in Vue?

Spread the love

To fix push to Vuex store array not working in Vue, we commit a mutation.

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 define our Vuex store with the addCustomer mutation.

In it, we call state.customers.push to append customer as the last item of the customers state.

Then we write

store.commit("addCustomer", { id: "2", name: "User 2" });

to call store.commit with the name of the mutation to commit and the object we want to append to the 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 *