-1

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;
Dave B
  • 21
  • 1
  • 5

1 Answers1

-1

Added token to the useEffect dependencies, this causes it to load the token when rendered. A problem with this is after the first render, the token becomes blank again, but if you're using it to just log a user in on render, this would work just fine.

  useEffect( ()=> {
    getScores();
    logInUserIfReturning();
  },[token])
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
gavin
  • 1,224
  • 5
  • 17