From 701a9762cfd87f8239a94510275fa1b91f8a71dd Mon Sep 17 00:00:00 2001 From: Tyrel Souza Date: Mon, 26 Sep 2022 13:31:06 -0400 Subject: [PATCH] grouping items --- ordering/src/store/CartProvider.js | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/ordering/src/store/CartProvider.js b/ordering/src/store/CartProvider.js index 3a47e27..cb6c8f7 100644 --- a/ordering/src/store/CartProvider.js +++ b/ordering/src/store/CartProvider.js @@ -8,9 +8,25 @@ const defaultCartState = { const cartReducer = (state, action) => { if (action.type === "ADD") { - 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 updatedItems + if (existingCartItem) + { + const updatedItem = { + ...existingCartItem, + amount: existingCartItem.amount + action.item.amount + } + updatedItems = [...state.items] + updatedItems[existingCartItemIndex] = updatedItem + } else { + updatedItems = state.items.concat(action.item) + } + return { items: updatedItems, totalAmount: updatedTotalAmount,