diff --git a/src/store/CartProvider.js b/src/store/CartProvider.js index baafa91..9c2a6b6 100644 --- a/src/store/CartProvider.js +++ b/src/store/CartProvider.js @@ -33,7 +33,34 @@ const cartReducer = (state, action) => { } return { items: updatedItems, totalAmount: updatedTotalAmount }; - } else if (action.type === "REMOVE_ITEM") { + } + + if (action.type === "REMOVE_ITEM") { + const existingCartItemIndex = state.items.findIndex( + (item) => item.id === action.id + ); + + const existingCartItem = state.items[existingCartItemIndex]; + + let updatedTotalAmount = state.totalAmount; + if (existingCartItem) { + updatedTotalAmount = state.totalAmount - existingCartItem.price; + } + + let updatedItems; + if (existingCartItem.amount === 1) { + // remove the item from array because this is the last item + updatedItems = state.items.filter((item) => item.id !== action.id); + } else { + const updatedItem = { + ...existingCartItem, + amount: existingCartItem.amount - 1, + }; + updatedItems = [...state.items]; + updatedItems[existingCartItemIndex] = updatedItem; + } + + return { items: updatedItems, totalAmount: updatedTotalAmount }; } return defaultCartState; };