Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React State wasn't changed after I clicked a switch to send a current state to server

Would you please explain this to me why it’s sending relay1 state with false? Why handleControlRelay1 doesn’t change the state
I’m doing it wrong by putting this inside a function? setRelay1((prevValue) => !prevValue);

// ...

  const [relaysData, setRelaysData] = useState([]);
  console.log("🚀 ~ file: Home.page.js:11 ~ HomePage ~ relaysData", relaysData);
  const [relay1, setRelay1] = useState(null);
  console.log("🚀 ~ file: Home.page.js:12 ~ HomePage ~ relay1", relay1);

  const handleControlRelay1 = () => {
   console.log("before setRelay1", relay1);
   setRelay1((prevValue) => !prevValue);
   console.log("after setRelay1", relay1);
    axios
      .put(`http://localhost:4000/relays/1`, {
        id: 2,
        name: "Superman",
        state_1: relay1,
        state_2: false,
        state_3: false,
        type: "switch-1",
      })
      .then((response) => {
        console.log(response.data.message);
      })
      .catch((error) => {
        console.log(error.message);
      });
  };

 useEffect(() => {
    fetchRelaysData();
  }, []);

  useEffect(() => {
    if (!!relaysData) {
      let { state_1 } = relaysData;
      setRelay1(state_1);
    }
  }, [relaysData]);

return (
   <FormControlLabel
              control={
                <Switch
                  checked={!!relay1}
                  onChange={handleControlRelay1}
                />
              }
              label="ZarĂłwka 1"
            />
       )

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The console.log will not work as expected because setstate is asynchronous.

This will send the right value to the backend:

const handleControlRelay1 = () => {
  console.log("before setRelay1", relay1); 
  const newRelayValue = !relay1
  setRelay1(newRelayValue);
  console.log("after setRelay1", relay1);
  axios
    .put(`http://localhost:4000/relays/1`, {
      id: 2,
      name: "Superman",
      state_1: newRelayValue,
      state_2: false,
      state_3: false,
      type: "switch-1",
    })
    .then((response) => {
      console.log(response.data.message);
    })
    .catch((error) => {
      console.log(error.message);
    });
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading