0

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?

crevulus
  • 1,658
  • 12
  • 42
  • 1
    Try `const newArray = [...selectedTestimonials]` – Nadia Chibrikova Feb 06 '21 at 14:39
  • Don't mutate state in React – CertainPerformance Feb 06 '21 at 14:40
  • @NadiaChibrikova that works, thanks. Why does that work, though? I get that the spread operator creates a shallow copy but what does that have to do with updating state? Especially as the console log worked just fine. – crevulus Feb 06 '21 at 14:44
  • The problem with `newArray = selectedTestimonials` is that it doesn't do anything useful - it allows you to access the same variable using a different name, but when you try to update the state, React ignores it, because you updating to the same thing. You mutate your current state instead of creating a new one. – Nadia Chibrikova Feb 06 '21 at 14:50
  • Ah so `newArray = selectedTestimonials` is essentially just storing a pointer to that state variable in memory and calling it "newArray" instead of actually creating a new array? That makes sense. Thank you. – crevulus Feb 06 '21 at 15:13

0 Answers0