1

In the React Native App, after I click the toggle button, the function _toggleServerSwitch gets triggered. Then I change the state serverSwitchValue to the same value as x.

Expected: serverSwitchValue and x should have the same value when console.log().

Actual: When console.log(), the two variables have different values.

It seems that the program works, but at the time when console.log() gets triggered, the values are not the same. Why?

const [serverSwitchValue, setServerSwitchValue] = useState(false);

  const _toggleServerSwitch = x => {
    setServerSwitchValue(x);
    console.log('x is: ' + x);
    console.log('serverSwitchValue is: ' + serverSwitchValue);
  };
M. We
  • 13
  • 2
  • 1
    Does this answer your question? [Strange behavior of React hooks: delayed data update](https://stackoverflow.com/questions/55983047/strange-behavior-of-react-hooks-delayed-data-update) – leverglowh Jan 14 '20 at 09:32

1 Answers1

1

setServerSwitchValue() is an async function , so it doesnt imply that you will get the values updated instantly. YOu can use useEffect as below :

useEffect(() => {
 console.log(serverSwitchValue);
}, [serverSwitchValue]); // Only re-run the effect if open changes

Hope it helps.

Gaurav Roy
  • 11,175
  • 3
  • 24
  • 45