I am trying to add a functionality that remove an item from the shopping cart component by clicking the onClick that fires the removeProductFromCartAtIndex useCallback function. So far I managed to add items to the shopping cart successfully but when I use the onClick to remove it deletes the whole shopping cart array.
I would like to remove items from the shopping cart at index using the useCallback hook
I feel like I am updating the state incorrectly. I know it would be easier if I filter out an actual item id instead of index, I am trying to understand how I can filter the array using index.
Thank you in advance for any help or advice!
context.js file:
const [shoppingCart, setShoppingCart] = React.useState([]);
const removeProductFromCartAtIndex = React.useCallback((index) => {
setShoppingCart(shoppingCart.filter((item, i) => i !== index
}, []);
shopping-cart.js file:
const ShoppingCart = () => {
const {shoppingCart, actions} = useContext(AppContext)
return (
<div className="shopping-cart">Shopping Cart
<ul>
{shoppingCart.map((item, index) => (
<li key={index}>
<span className='count'>1</span>
<span>{item.name}</span>
<span>$0.00</span>
<button onClick={() => {actions.removeProductFromCartAtIndex(index)}}><VscTrash /></button></li>
))}
</ul>
There are two things you need to fix:
setShoppingCart
as a dependency touseCallback
.So your code should look like:
In general whey you're updating a state variable, and the new state value depends on the previous value, you want to use a functional state update. Otherwise you're risking using a stale value.