0

import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;

user return null !!

and this not

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;
    console.log(user.email);
    // ...
  } else {
    // User is signed out
    // ...
  }
});

2 Answers 2

0

What you're seeing seems like the expected behavior to me.

When you access auth.currentUser, it gives you the current user when that code runs. Firebase automatically restores the user's credentials when a page loads and this requires a call to the server. This means that when your auth.currentUser runs, that call may not have completed yet, and thus the current user is null.

When on the other hand you use onAuthStateChanged, Firebase only calls your code when it has completed the first check of the user's credentials. So now your code runs after the user has been signed in, and user is no longer null.

This is one of the main reasons it's almost always better to use an auth state listener.

3
  • what is this 'auth stte listener' ? Commented Jun 10, 2021 at 19:43
  • Sorry, that was a typo. An auth state listener is what you add with onAuthStateChanged. Commented Jun 10, 2021 at 20:08
  • oh well, am sorry i am from latan a think what 'auth stte listener' is a function wat me idk Commented Jun 11, 2021 at 22:50
0

You could use either of these:

this.user$ = authState(auth);

OR

this.user$ = new Observable((observer: any) =>
  onAuthStateChanged(auth, observer)
);

OR

this.user$ = user(auth);

and get the Promise version like so:

const user = await this.user$.pipe(take(1)).toPromise();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.