1

I have a very simple problem and I'm stuck:

  • I have a simple MUI react switch with state tracker
  • It doesn't work first time, but it works all subsequent times... EDIT: specifically the state is not updated the first time, the lgos show false, false, true, false, true instead of false, true, false, true etc
const [checked, setChecked] = useState(false);
  const handleChange = () => {
    setChecked(!checked);
    if(image.file != null){
      displayImage(image.file);
    }
  };
<FormGroup>
<FormControlLabel control={<Switch checked={checked} onChange={handleChange} color="secondary"/>} label="Center Image" />
</FormGroup>
Ablomis
  • 157
  • 1
  • 1
  • 6
  • Can you clarify what doesn't work the first time? Is the switch not being checked on the first click? The MUI switch worked fine as I tested the code (without the image part). If the problem is with showing the image, this example does not provide information on where the problem could be other than `image.file` being null or `displayImage` not doing what you intend it to do. – hilipati Mar 23 '22 at 06:55
  • It doesnt update state, logs showing: false, false, true, false, true etc... instead of false, ture, false, true.. The rest works perfectly (image display etc) maybe the problem is somewhere else then.. – Ablomis Mar 23 '22 at 07:00
  • 1
    The answer is here - https://stackoverflow.com/a/66039282/2822041 – Someone Special Mar 23 '22 at 07:05

1 Answers1

0

This will make it work:

  const handleChange = () => {
    setChecked(!checked);
  };

and

  useEffect(()=>{
    if(image.file != null){
      displayImage(image.file);
    }
  }, [checked]);
Ablomis
  • 157
  • 1
  • 1
  • 6