'How to delete an item in react

I have opened the dialogue box on the delete button and when ok is pressed deleteFruit is called, id is passed to it.

function fruits{
 let data = [{id:1, name:'grapes'},{id:2, name:'orange'}]
 const [openDialog, setOpenDialog] = useState(false)
 const deleteFruit= (id) =>{alert(id)}

  function exampldata() {
    return ( {data.map(item ={
         return <button onClick={()=>setOpenDialog(true)}>Delete</button>
      })
   } 

 return (
    <>
       {exampldata()}

       <Dialog open={open}>       
        <Button   onClick={handleClose} > Cancel</Button>
          <Button  onClick={deleteFruit}>Ok</Button>          
        </DialogActions>
      </Dialog> 
   </>
 )
}


Solution 1:[1]

You just need to filter the data based on the id you have passed. And that will remove the item you want to remove.

But make sure you keep your data in a state variable so that your view re-renders when you update it using setData.

 const [data, setData] = useState([{id:1, name:'grapes'},{id:2, name:'orange'}]);

 const deleteFruit= (id) =>{           
   const tempData = data.filter(item => item.id !== id); // this will remove the item which matches the id
   setData(tempData);
 }

Solution 2:[2]

Maintain state for delete ids. Add to set when deleted and filter the deleted items while render.

function fruits() {
  let data = [
    { id: 1, name: "grapes" },
    { id: 2, name: "orange" },
  ];
  const [openDialog, setOpenDialog] = useState(false);
  const [deleted, setDeleted] = useState(new Set());
  const deleteFruit = (id) => {
    setDeleted(deleted.add(id));
  };

  function exampldata() {
    return (
      <div>
        {data
          .filter((item) => !deleted.has(item.id))
          .map((item) => (
            <button onClick={() => setOpenDialog(true)}>Delete</button>
          ))}{" "}
      </div>
    );
  }

  return (
    <div>
      {exampldata()}

      <Dialog open={open}>
        <Button onClick={handleClose}> Cancel</Button>
        <Button onClick={deleteFruit}>Ok</Button>
      </Dialog>
    </div>
  );
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Siva K V