0

The result string from the fetch is strangely not written via setStat in the stat variable, but when I output the result in the console inside fetch then that is the expected correct value (online), do you have an idea why useState "stat" remains empty?

const [stat, setStat] = React.useState("");

...

        fetch("https://123.321:4040/app/requestStat", requestOptions)
          .then(response => response.text())
          .then(result => console.log("Fetch response:" + result)) // <- correct value
          .then(result => setStat(result))
          .catch(error => console.log('error', error));

          console.log("stat value: " + stat); // <- empty value ??

...

// console.log output
stat value:                  Eva.js:177:18
Fetch response:online        Eva.js:173:34
  • (1) The console.log is being invoked immediately after fetch and doesn't wait for a response, and (2) even if you await the fetch request, `setStat` does not update `stat` immediately as react "batches" state updates into the next render for performance reasons. – Terry Oct 16 '22 at 23:00
  • For one thing it's asynchronous, the new value isn't assigned to `stat` until _next_ time the component gets rendered. – jonrsharpe Oct 16 '22 at 23:01
  • 1
    You're returning the output of the `console.log` which is undefined and returning it to the `.then()` that sets the value. – miklando Oct 16 '22 at 23:01
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Terry Oct 16 '22 at 23:01
  • this is fired in a routine every 10 seconds, then the stat should be filled in the next run, even if first asynchronous? – flying_kaktus Oct 16 '22 at 23:02

0 Answers0