I'm practicing React, developing a Store, for adding the feature of the Shopping Cart I use this example.
But in my implementation, even though my version is almost the same, the "add to cart" button doesn't differentiate between each product, meaning:
- 1st click affect all the buttons not only the clicked one and the other buttons change to "add more" legend
- each posterior click only adds more products of the same kind the user 1st clicked, ignoring if clicked another one.
Seems the error its caused by a mutation in a Reducer Function:
export const CartReducer = (state, action) => {
switch (action.type) {
case 'ADD_ITEM':
if (!state.cartItems.find((item) => item.id === action.payload.id)) {
//-------HERE
state.cartItems.push({
//mutation here?
...action.payload,
quantity: 1,
});
//-------
}
return {
...state,
...sumItems(state.cartItems),
cartItems: [...state.cartItems],
};
What would be an alternative to this? How do I push items in the state without a mutation?
The complete te file its here
Here you can check the deploy and replicate the error, and here its the correct functionality demo