add complex reducer logic for remove cart item

This commit is contained in:
oscar 2023-03-18 23:06:16 +13:00
parent e2dfadc739
commit 5c6e1d778c

View File

@ -33,7 +33,34 @@ const cartReducer = (state, action) => {
} }
return { items: updatedItems, totalAmount: updatedTotalAmount }; 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; return defaultCartState;
}; };