Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
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"
           />
  )
}
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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);
  }
}
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!