Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

Accessing the updated state in useEffect doesn't work

$
0
0

I need to fetch two API-endpoints in the useEffectcall, where the second call uses the result of the first call.

So currently I have:

const [steamID, setSteamID] = React.useState<string>();const [loading, setLoading] = React.useState(true);  React.useEffect(() => {    setLoading(true);    getLoggedInUser()      .then((userObj) => userObj?.steamID)      .then((fetchedSteamId) => {        setSteamID(fetchedSteamId);        console.log("steamID1: " + steamID);        console.log("steamID2: " + fetchedSteamId);      }).then(         // second API-Call which needs steamID         // by either using steamID(state) or fetchedSteamId(result)      )      .catch((err) => {        setLoading(true);      });}, []);

I tried to append another .then() before the .catch() where I access the steamID state. But already with the code provided I have the following output:

steamID: undefinedsteamID: 1234567891011

So when updating my state steamID inside useEffect, it will be undefined when accessed within useEffect unless i make any changes with hot-reload. The second output will always be correct.

I sure could just always pass the result further down, but is this the proper way? And how can I make sure, afteruseEffect, my state contains the correct values?


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>