I am having some trouble with my implementation of Firebase, using their FirebaseUI. On my login.html page I initializing my default app with my configs but then when I am redirected to my main.html page it seems like I have to initializing a second app because it cant recognize my first load. No problem with that except that I am losing information about the current user who's logged in through my first app initializing.
Anyone know how to either skip the need of redoing the initializing or how to "transfer" current logged in user to the second app?
If you're loading a new page, you will indeed need to re-initialize Firebase on that new page, as there is no "memory" in the browser of what was active on the previous page. If you want to prevent this reload, look into building a single-page application, which makes both screens part of the same page.
Firebase Authentication will automatically store the user credentials inn local storage, and try to restore them on the new page. This requires it to call to the server though, which means that firebase.auth().currentUser is typically not initialized right when the page loads. Instead, you'll want to add an auth state listener as shown in the first code snippet in the documentation on getting the current user.
For the v9 and up modular SDK syntax:
import { getAuth, onAuthStateChanged } from "firebase/auth";
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
const uid = user.uid;
// ...
} else {
// User is signed out
// ...
}
});
For v8 and before:
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
var uid = user.uid;
// ...
} else {
// User is signed out
// ...
}
});