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

131
Visualizações
how to add/remove data to state depending on if the checkbox was checked and then unchecked

I am currently trying to get the values from checkboxes, ids, so that I can do some logic and store them on a db. What I am trying to do is something like a week calendar, and if you click on one, it means you selected that day, for example id: 1 = Sun, but if I click it again I don't want it to duplicate the id, I rather want it to not be selected meaning, remove it. This is what I have done, I even tried using sets but it is not working(the set adds and removes stuff, but the issue is clearly on the (prev) => [...]) that is what I think it is what i am doing wrong so I think I just need some recommendation on how to do it.

const [dayId, setDayId] = useState([]);

{days.map((day, idx) => (
                <input onChange={(e) => {
                    let checked = e.target.value;
                    const values = new Set();
                    setDays(
                        days.map(data => {
                            if (data.id === day.id) {
                                let value = e.target.value;
                                data.id = value;
                                if(data.select === false) {
                                    data.select = true;
                                }
                                else {
                                    data.select = false;
                                }
                            }
                            return data;
                        })
                    );
                    if(values.has(checked)) {
                        values.delete(checked);
                    }
                    if(e.target.checked === true) {
                        values.add(checked);
                    }
                    if(e.target.value === false) {
                        values.delete(checked);
                    }
                    setDayId(prev => {
                        return [...prev, ...values]
                    })
                    console.log("CHECKING CHECKED VALUE", e.target.checked);
                    console.log("WHAT IS THE SET VALUE", values)
                }} key={idx} name={day?.name} type="checkbox" value={day?.id} checked={day.select}  />
            ))}

In summary, I want that array to add remove values depending if they were checked and then unchecked, the set actually does it, but the values are not kept so that is why I did this, setDayId(prev => {return [...prev, ...values]}), but that right there keeps the values and never removes them and even duplicates them. Any help would be greatly appreciated.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If I'm understanding your question you basically want to add the id if checked is true, and remove the id if checked is false, from the dayId state. In setDayId check the checked value and if true then shallow copy the dayId state and append the new id (value), otherwise remove it from the dayId array using a .filter function.

{days.map((day, idx) => (
  <input
    onChange={(e) => {
      const { checked, value } = e.target;

      setDays(
        days => days.map(data => {
          if (data.id === day.id) {
            return {
              ...data,
              id: value,
              select: !data.select,
            };
          }
          return data;
        })
      );
    
      setDayId(prev => {
        return checked
          ? [...prev, value]                  // add if checked
          : prev.filter(val => val !== value) // remove if not checked
      });

      console.log("CHECKING CHECKED VALUE", e.target.checked);
      console.log("WHAT IS THE SET VALUE", values)
    }}
    key={idx}
    name={day?.name}
    type="checkbox"
    value={day?.id}
    checked={day.select}
  />
))}
about 4 years ago · Juan Pablo Isaza 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