From 5c6e1d778cbc3ad81bc55e48bff0699fc593e797 Mon Sep 17 00:00:00 2001 From: oscar Date: Sat, 18 Mar 2023 23:06:16 +1300 Subject: [PATCH] add complex reducer logic for remove cart item --- src/store/CartProvider.js | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) 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; };