When we want to use the current authenticated user, we need to listen to the firebase auth state:
firebase.auth().onAuthStateChanged((user) => { ... });
Are there some cases that using the firebase.auth().currentUser api is the right choice (and not bed practice)?
firebase.auth().currentUser is primarily used to get the properties of the currently signed-in user.
These properties include displayName email emailVerified phoneNumber uid and many more.
I suspect that the correct way of using both method is in a high level component in your project. What does this mean?
Well, assume we have a webapp using Firebase Auth.
When the user visits this webapp, I'd like to check if he's logged in. And so I'll add onAuthStateChanged to register an authentication event handler that responds to changes in the authentication state. This should be added in one of my webapp's top level components.
If the user is null (this means no user is logged in, I'll redirect the user to my login page).
But if the user != null then I'd like to store some info about this user on an app-wide level in order to then use this user's info all around my webapp in whatever components I want. And so we can pass the redux state some of the user props. My code will be:
//
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;
// ... SET REDUX STATE
} else {
// User is signed out
// ... window.location.href = '/login'
}
});
Theoretically speaking, you could use firebase.auth().currentUser throughout your webapp. However it's generally considered to be bad practice because you'll trigger an intermediate state when you don't have to. If you just set the user's properties to the redux state from the beginning, no intermediate state will appear once you want to use the user's info within your webapp.