0

Im trying to access an Variable (that is initialized with useState) every 3 seconds. But the Variable isn't updated inside the function, when the value Variable changes. The same happens when the Variable is given as prop. The Variable itself changes, as seen by the <p>.

I've tried different methods to log the var, but everytime it logs the value that the var had when startInterval was called and not the value, it should have at that moment.

export function Test() {
  let [testState, setTestState] = useState(false);

  function startInterval() {
    // interval = setInterval(() => console.log(props.isLoggedIn), 3000);  //Doesn't work as well
    recursiveTest2()
  }

  async function recursiveTest1() {
    await new Promise(resolve => setTimeout(resolve, 3000))
    console.log(props.isLoggedIn);
    recursiveTest1();
  }

  async function recursiveTest2() {
    new Promise(resolve => setTimeout(resolve, 3000)).then(() => {
      console.log(testState);
      recursiveTest2();
    })
  }

  function toggelTestvariable() {
    setTestState(!testState);
    console.log(testState)
  }


  return ( 
    <div>
      <p> { testState.toString() } </p> 
      <button onCLick = { toggleVariable }>ToggleVariable</button>
    </div>
  )

}
Pascal
  • 87
  • 1
  • 1
  • [Read this](https://dmitripavlutin.com/react-hooks-stale-closures/). And also [this from the official React FAQ](https://reactjs.org/docs/hooks-faq.html#why-am-i-seeing-stale-props-or-state-inside-my-function) – Jared Smith Apr 07 '21 at 12:30
  • 1
    Thanks a lot. That articles helped me lot learning about the Problem. – Pascal Apr 08 '21 at 06:48

0 Answers0