PNG
PNG

Reputation: 285

React hooks - Remove multi object from array and update state

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

Upvotes: 0

Views: 1017

Answers (1)

rMonteiro
rMonteiro

Reputation: 1696

You can simplify it to a single filter function:

const DeleteProducts = () => {
  setProducts(prevProducts => {
    return prevProducts.filter(p => ! p.selected);
  });
}

Upvotes: 3

Related Questions