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.