remove item
This commit is contained in:
parent
701a9762cf
commit
5f88a979a7
@ -11,8 +11,13 @@ function Cart(props) {
|
||||
const totalAmount = `$${cartCtx.totalAmount.toFixed(2)}`
|
||||
const hasItems = cartCtx.items.length > 0
|
||||
|
||||
const cartItemRemoveHandler = id => {}
|
||||
const cartItemAddHandler = items => {}
|
||||
const cartItemRemoveHandler = (id) => {
|
||||
cartCtx.removeItem(id)
|
||||
|
||||
}
|
||||
const cartItemAddHandler = (item) => {
|
||||
cartCtx.addItem({ ...item, amount: 1 })
|
||||
}
|
||||
|
||||
const cartItems = (
|
||||
<ul className={classes["cart-items"]}>
|
||||
|
@ -15,11 +15,10 @@ const cartReducer = (state, action) => {
|
||||
)
|
||||
const existingCartItem = state.items[existingCartItemIndex]
|
||||
let updatedItems
|
||||
if (existingCartItem)
|
||||
{
|
||||
if (existingCartItem) {
|
||||
const updatedItem = {
|
||||
...existingCartItem,
|
||||
amount: existingCartItem.amount + action.item.amount
|
||||
amount: existingCartItem.amount + action.item.amount,
|
||||
}
|
||||
updatedItems = [...state.items]
|
||||
updatedItems[existingCartItemIndex] = updatedItem
|
||||
@ -31,6 +30,27 @@ const cartReducer = (state, action) => {
|
||||
items: updatedItems,
|
||||
totalAmount: updatedTotalAmount,
|
||||
}
|
||||
} else if (action.type === "REMOVE") {
|
||||
const existingCartItemIndex = state.items.findIndex(
|
||||
(item) => item.id === action.id
|
||||
)
|
||||
const existingCartItem = state.items[existingCartItemIndex]
|
||||
const updatedTotalAmount = state.totalAmount - existingCartItem.price
|
||||
let updatedItems
|
||||
if (existingCartItem.amount === 1) {
|
||||
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
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user