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([]);

    auth.isAuthenticated();

The “isAuthenticated” function in “auth” is

    isAuthenticated() {
      this.checkStatus();
      console.log(this.authenticated)
      return this.authenticated;
    }

Referring to checkStatus which is

    checkStatus(){
      let cookie = this.getCookie("mycookie");
      
      fetch('myCheckURL', {
        method: 'POST',
        headers: {
          'Authorization': cookie
        }})
      .then(response => response.json())
      .then(data=>{
        if(data["code"]==="200")
        {
            this.token = cookie;
            return this.authenticated = true;            
        }
        else
        {
            return this.authenticated = false;
        }

      }).catch(error=>{
          console.error('Error:',error);
      })      
    }

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();
      console.log(this.authenticated)
      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.