React remove items from the shopping cart at index using the useCallback hook

836 views Asked by At

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>
1

There are 1 answers

0
fpgx On

There are two things you need to fix:

  1. Add setShoppingCart as a dependency to useCallback.
  2. Use a functional state update.

So your code should look like:

const removeProductFromCartAtIndex = React.useCallback((index) => {
  setShoppingCart(currentShoppingCart => currentShoppingCart.filter((item, i) => i !== index
}, [setShoppingCart]);

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.