samedi 6 février 2021

useState array only updating on checkbox checked === true [duplicate]

When a user checks a box in a child component I'm pushing values to an array that I'm storing in state:

const [selectedTestimonials, setSelectedTestimonials] = useState([]);

// largely irrelevant, just adding selected testimonials from props into component state
useEffect(() => {
  testimonialsData.forEach((testimonial) => {
    if (testimonial.show === true) {
      setSelectedTestimonials((prevState) => [
        ...prevState,
        testimonial.testimonialId,
      ]);
    }
  });
}, []);

const handleCheckboxChange = (boolean, id) => {
  if (boolean === true) {
    setSelectedTestimonials((prevState) => [...prevState, id]);
  } else {
    const newArray = selectedTestimonials;
    const elementIndex = newArray.find((element) => element === id);
    newArray.splice(newArray.indexOf(elementIndex), 1);
    console.log(newArray);
    setSelectedTestimonials(newArray);
  }
};

Trouble is, state only gets updated when checked === true. If the user unchecks a box, state is not updated. That console.log, though, is printing the correct array of ids when a user unchecks. So the array splicing/adding logic is just fine. The only issue is updating state.

Any ideas why state wouldn't update when I uncheck, but it updates successfully when I check?




Aucun commentaire:

Enregistrer un commentaire