Skip to content

Commit f583e42

Browse files
committed
Reconfigured reducer logic to accept duplicate items in our cart and evaluate it so that it only increases the count of duplicate items.
1 parent 34ea6e7 commit f583e42

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

specialtea/src/store/CartContext/CartProvider.js

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,28 @@ const defaultCartState = {
99

1010
const cartReducer = (state, action) => {
1111
if (action.type === 'ADD') {
12-
const updatedItems = state.items.concat(action.item);
1312
const updatedTotalAmount =
1413
state.totalAmount + action.item.price * action.item.amount;
1514

15+
const existingCartItemIdx = state.items.findIndex(
16+
item => item.id === action.item.id
17+
);
18+
19+
const existingCartItem = state.items[existingCartItemIdx];
20+
21+
let updatedItems;
22+
23+
if (existingCartItem) {
24+
const updatedItem = {
25+
...existingCartItem,
26+
amount: existingCartItem.amount + action.item.amount
27+
};
28+
updatedItems = [...state.items];
29+
updatedItems[existingCartItemIdx] = updatedItem;
30+
} else {
31+
updatedItems = state.items.concat(action.item);
32+
}
33+
1634
return {
1735
items: updatedItems,
1836
totalAmount: updatedTotalAmount,

0 commit comments

Comments
 (0)