React: Failure to await a Fetch-Function's response / Persistence

Hi folks,
Currently, I am working on a way to check if a user is already logged in. I do this by checking if a cookie is saved and, if the cookie is saved, compare it to an entry n the database through fetch. If it’s a match, a constructor called “isAuthenticaed” will be set true.
Now I call a function on my login-page.

import auth from './../auth';

const Login = (props) => {
    const [profile, setProfile] = useState([]);
    const [password, setPassword] = useState([]);
    const [email, setEmail] = useState([]);


The “isAuthenticated” function in “auth” is

    isAuthenticated() {
      return this.authenticated;

Referring to checkStatus which is

      let cookie = this.getCookie("mycookie");
      fetch('myCheckURL', {
        method: 'POST',
        headers: {
          'Authorization': cookie
      .then(response => response.json())
            this.token = cookie;
            return this.authenticated = true;            
            return this.authenticated = false;


I know through console logs that I get a positive results from my checkStatus function. But the timing is bad. Because the result I get is:

  • false
  • then I get the output.

So before the checksatus function is getting a result, isAuthenticaed moves on and says it’s false.

Two questions:

  • How can I change this so that it awaits the result of the function?
  • Why does it happen? I thought JS is a scripting language working line by line.

Thanks in advance for your replies.

hey @nucky ,

you could try this

 async isAuthenticated() {
     await this.checkStatus();
      return this.authenticated;

how id do it…

async checkStatus() {
  let cookie = this.getCookie("mycookie");

  const response = await fetch("myCheckURL", {
    method: "POST",
    headers: {
      Authorization: cookie,

  const data = await response.json();

  if (data["code"] === "200") {
    this.token = cookie;
    return true;
  } else {
    return false;
 async isAuthenticated() {
     const authenticated = await this.checkStatus();
      return authenticated;

Biscuitmanz, this! So simple, so elegant? Thank you so much. I could kiss you. It works, it seems to work. I tried it two times, also restarted the local machine. It works. I was close with using “await” in front of this.checkStatus();. But it works.

1 Like

I considered such an approach. But wouldn’t this let my app always send a request to the server when changing the pages, moving between protected and unprotected pages?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.