add complex reducer logic (crucial!)
This commit is contained in:
parent
cee3570ef0
commit
cada9d84fb
@ -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") {
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user