简体   繁体   中英

React checkboxes don't reset after submitting form

I'm quite new to React, so I decided to make a skincare app to learn the beast. I thus made a form to register the products, and this form contains checkboxes. My problem is, I cannot for the life of me get them to reset (empty?) after submitting the form. All the answers I've found were either too old or didn't work.

//Frequency
  const [isDayChecked, setDayChecking] = useState([]);

  const dayFrequencyHandler = (event) => {
    const { value, checked } = event.target;
    // Case 1 : The user checks the box
    if (checked) {
      setDayChecking((checkedDays) => [...checkedDays, value]);
    }
    // Case 2  : The user unchecks the box
    else {
      setDayChecking(isDayChecked.filter((e) => e !== value));
    }
  };

  const [isNightChecked, setNightChecking] = useState([]);

  const nightFrequencyHandler = (event) => {
    const { value, checked } = event.target;
    // Case 1 : The user checks the box
    if (checked) {
      setNightChecking((checkedNights) => [...checkedNights, value]);
    }
    // Case 2  : The user unchecks the box
    else {
      setNightChecking(isNightChecked.filter((e) => e !== value));
    }
  };

As you can see, these checkboxes are used to register at what frequency the products are going to be used (one checkbox for the morning and one for the night, for each day of the week). The data is then stored into the empty array of useState(), or removed when the user unchecks its box. That part works fine.

What doesn't work fine though, is my submit function that refuses to clear the checkboxes once called. The most logical solution to me would be to reset the checkboxes' state to their original, well, state, like this:

const submitHandler = (event) => {
    event.preventDefault();

    setDayChecking([]);
    setNightChecking([]); 
  };

React obviously disagrees, since it does't work. I've tried using the same code than when the user unchecks the box (would be something like this:

setDayChecking(() => {
      const { value } = event.target;
      isDayChecked.filter((e) => e !== value);
    });
    setNightChecking(() => {
      const { value } = event.target;
      isNightChecked.filter((e) => e !== value);
    });

) but it's even worse.

Does anyone has any idea what I'm doing wrong? Thanks in advance!

I had similar error when I first used with checkbox . I think you forgot to add checked attribut at input . Add a boolean value to checked .

<input type={"checkbox"} value={"some_value"} checked={dayChecking.includes("some_value")} />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM