Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

145
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda