Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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}
  />
))}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading