0

How to delete multiple objects of array and update the 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 show remaining items except 3 selected items in products state? Thanks

1

1 Answer 1

3

You can simplify it to a single filter function:

const DeleteProducts = () => {
  setProducts(prevProducts => {
    return prevProducts.filter(p => ! p.selected);
  });
}
Sign up to request clarification or add additional context in comments.

Comments

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.