Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda