Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want my aysnc function to react to state change so that it can terminate upon state change. What I have discovered is that it doesn't react to changing the state.

In the provided example I am changing the state from inside of the function, however I have tested it and changed the state from outside of function (Button click) and it doesn't work either.

const [testVariable, setTestVariable] = useState(false);

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

const testFunction = async () => {
  await timeout(1000);

  console.log("Setting test variable to: " + true);
  setTestVariable(true);

  await timeout(1000);
  
  console.log("Test variable is: " + testVariable);
}

Expected result is to see that the variable changed to true, however what I see is: enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
197 views
Welcome To Ask or Share your Answers For Others

1 Answer

State variables never change their values. (Note that you can, have, and should declare them with const because they don't change).

Subsequent invokes of the component function will get a new state variable with the same name and a different value.

Your testFunction function has closed over the old state variable.


I suspect you could solve this with a reference:

const [testVariable, setTestVariable] = useState(false);
const reference = useRef();
reference.current = testVariable;

… and then have your function test the value of reference.current instead of testVariable.


This does, however, feel like an XY Problem where the real solution is "Use the return value from the function you pass to useEffect to stop whatever it is you want to stop" (and use testVariable as a dependency of useEffect).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...