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.