2👍
When you push state.orderItem
you add a reference to it in the array. So when state.orderItem
changes, the element inside the array changes, because it (the element inside the array) is actually still pointing to the same (state.orderItem
) object.
You can push a shallow clone of the orderItem
object instead:
// mutations.js
export const addToCart = (state) => {
state.cart.push({...state.orderItem});
};
This way what is added to the array is a different object.
Note: you can do:
state.cart.push({...state.orderItem});
But this will only work if you never remove/add elements from/to the toppings
array directly after the addToCart
is called. That is, if you call resetToppings
before adding new elements to toppings
(which will work because resetToppings
assigns a new array).
If that’s not always the case, I mean, if you sometimes edit the toppings
array directly after the addToCart
is called, you might want to clone it as well:
state.cart.push(Object.assign({...state.orderItem}, {toppings: [...state.orderItem.toppings]}});