Home > other >  how to add/remove data to state depending on if the checkbox was checked and then unchecked
how to add/remove data to state depending on if the checkbox was checked and then unchecked

Time:12-31

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.

CodePudding user response:

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}
  />
))}
  • Related