diff --git a/src/store/CartProvider.js b/src/store/CartProvider.js index ac960e1..baafa91 100644 --- a/src/store/CartProvider.js +++ b/src/store/CartProvider.js @@ -8,9 +8,30 @@ const defaultCartState = { const cartReducer = (state, action) => { if (action.type === "ADD_ITEM") { - const updatedItems = state.items.concat(action.item); const updatedTotalAmount = state.totalAmount + action.item.price * action.item.amount; + + const existingCartItemIndex = state.items.findIndex( + (item) => item.id === action.item.id + ); + + const existingCartItem = state.items[existingCartItemIndex]; + let updatedItem; + let updatedItems; + + if (existingCartItem) { + updatedItem = { + ...existingCartItem, + amount: existingCartItem.amount + action.item.amount, + }; + + updatedItems = [...state.items]; + updatedItems[existingCartItemIndex] = updatedItem; + } else { + updatedItem = { ...action.item }; + updatedItems = state.items.concat(action.item); + } + return { items: updatedItems, totalAmount: updatedTotalAmount }; } else if (action.type === "REMOVE_ITEM") { }