Delete multiple items using checkbox in React

Viewed 117

I am using react as my frontend and fetch data from php/MySQL. I would like to be able to delete item or items if input checkbox and id. Currently, I can successfully check and delete individual item but can't delete multiple items even if it is checked.

delete function:

const[products, setProducts] = useState([])

const deleteProductById = () => {
  let arrayids = [];
  products.forEach((p) => {
  if (p.select) {
  arrayids.push(p.id);
 }
});
  axios.delete(`api-url/${arrayids}`)
  console.log(arrayids);
};

I am able console.log(arrayids) of each item if that item has been checked, but I am not sure what I'm missing.

input:

<input
  type="checkbox"
  value={product.id}
  name={product.id}
  onChange={(e) => {
  product.select = e.target.checked;
  setProducts(products);
  }}
 />

Button above form:

 <button
  onClick={() => {
  deleteProductById();
   }}
  >Delete All </button>
1 Answers

To answer my own question. I think I have overcomplicated the function a bit. I didn't really have to push each id selected to an array, all I had to do was check if the condition is true or false, then delete each condition that are true.

const deleteProductById = () => {
  products.forEach((product) => {
if (product.select) {
"fetch the product.id(use whatever api fetch methods"
 .then((res) => {
 console.log(res.data);
  getProducts();
 });

Everything else can stay the same.

Related