In most modern apps protected by authentication, you’ll need to get the currently logged in user before performing most actions.

This can lead to issues sometimes because Firebase does have a way to use the user synchronously, but it’s highly discouraged because at several points it might return undefined even when the user is successfully logged in.

To avoid these issues, it’s more practical to get the user asynchronoulsy, in the case of Firebase Auth, they provide a function called onAuthStateChanged() which takes the current authentication instance and a function as parameters.

It returns the currently logged in user, or undefined if no user is logged in.

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Auth, onAuthStateChanged, Unsubscribe } from '@angular/fire/auth';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit, OnDestroy {
  authSubscriber: Unsubscribe;

  ngOnInit() {
    this.authSubscriber = onAuthStateChanged(this.auth, async user => {
      if (user) {
        // Here we have the user and can safely use it.
      } else {
        // No user is logged in.
      }
    });
  }

  ngOnDestroy(): void {
    this.authSubscriber();
  }
}

The onAuthStateChanged function returns its own unsubscribe, so it’s always a good idea to call it and make sure we don’t leave an open subscription there.

By the way, do you want to jump-start your development using the Firebase modular SDK with AngularFire?

Download my free book that will take you from creating an app to properly using Firebase Auth and Firestore.

Download the book now