remove item

This commit is contained in:
Tyrel Souza 2022-09-26 13:37:48 -04:00
parent 701a9762cf
commit 5f88a979a7
No known key found for this signature in database
GPG Key ID: F3614B02ACBE438E
2 changed files with 30 additions and 5 deletions

View File

@ -11,8 +11,13 @@ function Cart(props) {
const totalAmount = `$${cartCtx.totalAmount.toFixed(2)}` const totalAmount = `$${cartCtx.totalAmount.toFixed(2)}`
const hasItems = cartCtx.items.length > 0 const hasItems = cartCtx.items.length > 0
const cartItemRemoveHandler = id => {} const cartItemRemoveHandler = (id) => {
const cartItemAddHandler = items => {} cartCtx.removeItem(id)
}
const cartItemAddHandler = (item) => {
cartCtx.addItem({ ...item, amount: 1 })
}
const cartItems = ( const cartItems = (
<ul className={classes["cart-items"]}> <ul className={classes["cart-items"]}>

View File

@ -15,11 +15,10 @@ const cartReducer = (state, action) => {
) )
const existingCartItem = state.items[existingCartItemIndex] const existingCartItem = state.items[existingCartItemIndex]
let updatedItems let updatedItems
if (existingCartItem) if (existingCartItem) {
{
const updatedItem = { const updatedItem = {
...existingCartItem, ...existingCartItem,
amount: existingCartItem.amount + action.item.amount amount: existingCartItem.amount + action.item.amount,
} }
updatedItems = [...state.items] updatedItems = [...state.items]
updatedItems[existingCartItemIndex] = updatedItem updatedItems[existingCartItemIndex] = updatedItem
@ -31,6 +30,27 @@ const cartReducer = (state, action) => {
items: updatedItems, items: updatedItems,
totalAmount: updatedTotalAmount, 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 return defaultCartState
} }