From cada9d84fbac55adb8103bb76367061d043a5b8d Mon Sep 17 00:00:00 2001 From: oscar Date: Sat, 18 Mar 2023 22:48:34 +1300 Subject: [PATCH] add complex reducer logic (crucial!) --- src/store/CartProvider.js | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) 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") { }