I am trying to achieve the following flow:
1. Wait for app to load
2. Check if user exists
2.1 If doesn't, sign-up as anonymous
2.1.1 Create new collection using user ID
2.2 If does, pull existing collection using user ID
Reading through the specs I found the following way to persist users Auth State:
firebaseInstance.auth().setPersistence(firebaseAuth.Auth.Persistence.LOCAL)
.then(function() {
// Existing and future Auth states are now persisted in the current
// session only. Closing the window would clear any existing state even
// if a user forgets to sign out.
// ...
// New sign-in will be persisted with session persistence.
return firebaseInstance.auth().signInAnonymously().catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
})
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
})
And later listen for the state change with:
firebaseInstance.auth().onAuthStateChanged(user => {
if (user) {
// User is signed in.
var isAnonymous = user.isAnonymous
var uid = user.uid
const test = firebaseInstance.auth().currentUser
// ...
debugger
} else {
// User is signed out.
// ...
}
// ...
})
My understanding I can imagine that when firebase finishes initialising it pulls user from IndexedDB, sign-in completes and the user's data becomes available. (please correct me if I am wrong)
The issue
Executing firebaseInstance.auth().currentUser
before the firebase finishes completing it's internal logic returns null
, this makes me wonder if it's possible to listen for event when firebase auth completes it's internal tasks --> check for the current user, and if even after that there is still no user --> signIn with a new anonymus one.
Confusion point P.S: I am also confused why triggering signInAnonymously() time after time still returns the same user ID. It makes me doubt if I actually picked up the "right" way to achieve the functionality. If somebody can came up with a better implementation of the functionality flow I will appreciate it a lot :)