Why does this Firebase web authentication function 'onAuthStateChanged' occasionally not fire?
The intention of this code is to use Firebase for Web (JavaScript) and automatically sign-up visitors to the website as an anonymous user, however if they created an account using email and the anonymous sign-in is ignored.
Symptoms of this issue are:
When this happens, the debug statements look like this:
loaded 4
loaded 5
loaded 6
loaded 7
loaded 8
~98% of the time this code works as intended but around 2% of the time is does not work at all and the user must close and reopen the tab and I can't figure out why. Does anyone know what's wrong?
console.log("loaded 4");
const analytics = getAnalytics(app);
console.log("loaded 5");
const db = getFirestore(app);
console.log("loaded 6");
const functions = getFunctions(app);
console.log("loaded 7");
const auth = getAuth();
console.log("loaded 8");
onAuthStateChanged(auth, (user) => {
console.log("initiate on auth state change")
if (user) {
console.log("signed is as something")
fuctionToLoadStuff();
let uid = user.uid;
const isAnon = user.isAnonymous;
if (isAnon == true) {
console.log("User is signed in anonymously as " + uid);
annonUserStuff(uid);
} else {
console.log("User is signed into an account as " + uid);
getProfile(uid);
}
} else {
console.log("signed is as nothing");
signInAnonymously(auth)
.then(() => {
const uid = auth.currentUser.uid;
console.log("Anon user acct created");
functionForANewAnonUser(uid);
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
console.log(errorMessage);
});
}
});