add complex reducer logic (crucial!)

main
oscar 2023-03-18 22:48:34 +13:00
parent cee3570ef0
commit cada9d84fb
1 changed files with 22 additions and 1 deletions

View File

@ -8,9 +8,30 @@ const defaultCartState = {
const cartReducer = (state, action) => { const cartReducer = (state, action) => {
if (action.type === "ADD_ITEM") { if (action.type === "ADD_ITEM") {
const updatedItems = state.items.concat(action.item);
const updatedTotalAmount = const updatedTotalAmount =
state.totalAmount + action.item.price * action.item.amount; 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 }; return { items: updatedItems, totalAmount: updatedTotalAmount };
} else if (action.type === "REMOVE_ITEM") { } else if (action.type === "REMOVE_ITEM") {
} }