grouping items

This commit is contained in:
Tyrel Souza 2022-09-26 13:31:06 -04:00
parent ce7158fc15
commit 701a9762cf
No known key found for this signature in database
GPG Key ID: F3614B02ACBE438E

View File

@ -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,