grouping items
This commit is contained in:
parent
ce7158fc15
commit
701a9762cf
@ -8,9 +8,25 @@ const defaultCartState = {
|
|||||||
|
|
||||||
const cartReducer = (state, action) => {
|
const cartReducer = (state, action) => {
|
||||||
if (action.type === "ADD") {
|
if (action.type === "ADD") {
|
||||||
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 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 {
|
return {
|
||||||
items: updatedItems,
|
items: updatedItems,
|
||||||
totalAmount: updatedTotalAmount,
|
totalAmount: updatedTotalAmount,
|
||||||
|
Loading…
Reference in New Issue
Block a user