I'm trying to check if a user is signed in or not, but I'm getting really inconsistent results that seem to have some sort of race condition involved. I basically took the code Google Developer Website:
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
client_id: 'my_client_id.apps.googleusercontent.com',
});
console.log(auth2.isSignedIn.get());
setTimeout(function(){console.log(auth2.isSignedIn.get())},50);
setTimeout(function(){console.log(auth2.isSignedIn.get())},500);
setTimeout(function(){console.log(auth2.isSignedIn.get())},1000);
});
For some reason, the first two return false, and the second to return true. I have double checked, and I am signed in, so it seems like the first two should be returning true. What am I missing her? I've looked at the documentation, and there doesn't seem to be anything that indicated something asynchronous happening, and I'm not sure what I should be waiting on before I can get a reliable result from the isSignedIn
call.
Maybe I missed it in the documentation somewhere (if I did, it'd be nice if someone could point it out to me), but it looks like you can use Promises to make sure the GoogleAuth instance is ready. Here's what I did to get a consistent result:
gapi.load('auth2', function() {
gapi.auth2.init({
client_id: 'my_client_info.apps.googleusercontent.com',
}).then(function(){
auth2 = gapi.auth2.getAuthInstance();
console.log(auth2.isSignedIn.get()); //now this always returns correctly
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With