Home > Software engineering >  currentUser is returning null
currentUser is returning null

Time:03-30

I have a react app using firebase auth for authentication.

After a person logs in, it redirects them to a books page. Here's the submitLogin handler

import { auth, firebase } from "./firebase";
async function googleLogin() {
    const provider = new firebase.auth.GoogleAuthProvider();
    await auth.signInWithPopup(provider).then(
      async (result) => {
        const token = await auth?.currentUser?.getIdToken(true);
        if (token) {
          localStorage.setItem("@token", token);
          navigate("/book-list");
        }
      },
      function (error) {
        console.log(error);
      }
    );
}

Then in the books page, I try getting currentUser so that I can call getIdToken(), but currentUser is returning null.

import { auth } from "./firebase";
const currentUser = auth.currentUser

Here's the firebase.js file:

import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';

const firebaseConfig = {...};

firebase.initializeApp(firebaseConfig);

const auth = firebase.auth();
export { auth, firebase };

How can I call currentUser from another file after a user is signed in?

CodePudding user response:

This is the expected behavior. Since the books page is a new page, the Firebase SDK will need to restore the authentication state from local storage, where it automatically persists it. This requires it to make a call to the server, to for example check if the account has been disabled. Since we can't block the page load, your main code continues to execute and sees that currentUser is null.

What you'll want to do instead is listen for the authentication state of the user, as shown in the first snippet in the documentation on getting the current user:

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
    // ...
  }
});

This callback will automatically fire when the user session has been restored, or when that failed, or when there was never a signed in user to begin with, or whenever the auth state changes, and is thus the perfect place to update your application for the latest authentication state.

  • Related