0

In the following example I declare a variable myVar with useState() hook. I am trying to check its value and according to this do some things. I know through the useEffect() hook that myVar has the value it is supposed to have. Though when I try to check if it's equal with some value in if statements, those comparisons are clearly calculated wrong. Is there some workaround to ckeck myVar variable's value? Thank you in advance!

const Example = () => {

    const [myVar, setMyVar] = useState(0);
    useEffect(() => {
        // Consoles the correct value
        console.log(myVar);
    }, [myVar])

    useEffect(() => {
        (async () => {
            if (!loading) {
                await runAnimation();
            }
        })()
    }, [loading])

    const runAnimation = async () => {
        setMyVar(myVar + 1);
        someFunction();
    }

    const someFunction = async () => {
        response = await controls.start();
        // Gets in wrong statements
        if (myVar === 0) {
            doZero();
        } else if (myVar === 1) {
            doOne();
        } else if (myVar === 2) {
            setMyVar(myVar - 1);
            doTwo();
        }
    }

    return (
        <div>
            <SomeComponents />
        </div>
    )

}
iagerogiannis
  • 337
  • 3
  • 16
  • please explain why "those comparisons are clearly calculated wrong". That's really not apparent from your code. The function where the comparison is happening isn't even called. – Christian Fritz Oct 25 '21 at 00:36
  • They are clearly calculated wrong, because through useEffect I see that myVar has value 1, but the doZero function gets called instead of the doOne. The app consists of many files and dependencies, I cannot upload the whole app. – iagerogiannis Oct 25 '21 at 00:41
  • 1
    Can you add the code where you call `someFunction`? The bug is probably caused by a stale closure variable, but there's no way to be more specific without seeing the code. – Nicholas Tower Oct 25 '21 at 00:48
  • 1
    Calling `setMyVar` is not going to change any local variables, so `someFunction` on the next line is still going to be working with the same values you had before you called it. Depending on what you're trying to do you could either modify `someFunction` to take in a parameter and you pass in the new value, or you could set it up to run the next time the component renders via a `useEffect` – Nicholas Tower Oct 25 '21 at 01:33

0 Answers0