简体   繁体   中英

React hooks - Remove multi items from array and update state

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

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM