'Adding and removing objects in state of a component

I have a list of check inputs, and when they are selected and deselected I am trying to add/remove them from the state. But Ive noticed when I deselect one the one I selected prior is the object removed from the state. I think this is because when the onChange function is called the state hasnt updated (although the UI has) but I dont understand how to have a full list of all the checks selected with the state lagging behind one value. Heres my input and onChange func:

const [selected, setSelected] = useState([]);
   
     const handleSelect = (e) =>
       !!DATA &&
       DATA.forEach((item, idx) => {
         let name = e.target.name;
         if (item.payerName === name && !selected.includes(item)) {
           setSelected([...selected, item]);
           return;
         } else if (item.payerName === name && selected.includes(item)) {
           // index varies
           let index = selected.indexOf(item);
   
           let clean = selected.splice(index, 1);
           setSelected(clean);
         }
       });
   
   
DATA.map((item, idx) => {
    return(
          <input
             name={item.payerName}
             type="checkbox"
             checked={selected.includes(item)}
             onChange={handleSelect}
             className="insurance-checkbox m-2 mt-3"
           />
  )
}


Solution 1:[1]

Try this:

const [selected, setSelected] = useState([]);

const handleSelect = (e) => {
  const { name } = e.target;
  const item = DATA.find(({ payerName }) => payerName === name);

  if (selected.includes(item)) {
    setSelected(selected.filter((s) => s === item);
  } else {
    setSelected([...selected, item]);
  }
}

or even better:

const handleSelect = (e) => {
  const { name, checked } = e.target;
  const item = DATA.find(({ payerName }) => payerName === name);

  if (checked) {
    if (!selected.includes(item)) { // probably not needed
      setSelected([...selected, item]);
    }
  } else {
    setSelected(selected.filter((s) => s === item);
  }
}

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