I have some code to check that a locally stored token is loaded, and other code that will recurse until it is. The problem is that even though it hits the code that runs setState setter, the variable does not seem to be updated.
In this example, I simplified a few things and replaced the boolean with string values to make sure there isn't an issue with truthy/falsy-ness.
import { useState, useEffect } from "react";
function App() {
const [isTokenLoaded, setIsTokenLoaded] = useState("no");
const [token, setToken] = useState("");
useEffect( ()=> {
getScores();
logInUserIfReturning();
},[])
const delay = (ms)=> {
return new Promise(function(resolve) { //returns a promise
setTimeout(function() {
resolve();
}, ms);
});
}
const logInUserIfReturning = async () => {
console.log("logInUserIfReturning");
setToken("TEST_TOKEN_VALUE");
setIsTokenLoaded("yes");
};
//wait for loading to complete, to resolve race condition
const getScores = async (daysAgo) => {
if (isTokenLoaded=="no") {
console.log("not loaded");
await delay(3000);
return await getScores(daysAgo);
}
else {
console.log("loaded", token);
return "SCORES";
}
}
return (
<div className="App"></div>
);
}
export default App;