-2

How to delete multiple items of array and set state? I have selected multiple items from checkbox. This is the selected item [5, 4, 3] I want to remove all items in array based on id and update the state. This is my code.

const [products, setProducts] = useState();

 const DeleteProducts = () => {
  const selectedItems = [5, 4, 3];

    selectedItems.forEach(function(p) {
      setProducts(products.filter(prd => prd.id !== p));
    });
}

Its removing only one item at time, but I selected 3 items. How to remove 3 selected items and products state? Thanks

2

1 Answer 1

1

You're calling setProducts ever iteration of the loop. You have to call setProducts after you filter them so that it only triggers state change once

const [products, setProducts] = useState();

 const DeleteProducts = () => {
  const selectedItems = [5, 4, 3];
  let newProducts;
    selectedItems.forEach(function(p) {
      newProducts = products.filter(prd => prd.id !== p);
    });
  setProducts(newProducts);
}

better yet you can filter it faster like this without looping


const DeleteProducts = () => {
  const selectedItems = [5, 4, 3];
  const newProducts = products.filter(prd => selectedItems.indexOf(prd.id) >= 0);
  setProducts(newProducts);
}

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this, also I think you forgot to instantiate an empty array in newProducts variable, because that will become undefined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.