Skip to content
Advertisement

Firebase authentication in ReactJS project – user null inside onAuthStateChanged

I’m tearing my hair out trying to setup email/password authentication through firebase. I’ve got my firebase configuration setup like so

// Firebase App (the core Firebase SDK) is always required and must be listed first
import firebase from "firebase/app";
//authenticaion module
import "firebase/auth";

// Add the Firebase products that you want to use
import "firebase/firestore";

var firebaseConfig = {
 // I've got my api key and other info copied from the console in here
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);


export const db = firebase.firestore();
export const app = firebase.auth();

I’ve got a sign-in form created that calls the following function:

import { app } from "../firebase/firebaseConfig";

  const createAccount = () => {
    app
      .createUserWithEmailAndPassword(email, password)
      .then((user) => {
        console.log("user created");
        console.dir(user);
      })
      .catch((error) => {
        console.log("something went wrong");
      });
  };

First problem: I’m not seeing the “user created” message, even though I can see the user being created in the Firebase Authentication console. I’m also not seeing the “something went wrong” message that would indicate an exception occurred.

Second problem: I’m trying to do a re-direct when the user signs in. To do this, I’ve setup a listener on the Firebase auth object as suggested in the docs:

firebase.auth().onAuthStateChanged((user) => {
  console.log("Inside listener");
  console.dir(user);
});

The problem is, I’m seeing the console message so the function is triggering but ‘user’ is always null in here even though the user is being created.

Firebase version: 8.2.1

Can anyone see what I’m missing here?

Advertisement

Answer

I found a solution in case anyone runs into a similar issue – the button that was triggering the submit was inside a html form and I was not calling event.preventDefault() and so the page was re-rendering and I believe this was causing the auth callback to work incorrectly. Working code –

  const createAccount = (event) => {
    event.preventDefault();
    app
      .createUserWithEmailAndPassword(email, password)
      .then((user) => {
        console.log("user created");
        console.dir(user);
      })
      .catch((error) => {
        console.log("something went wrong");
      });
  };
Advertisement