Garmaine Staff asked 2 years ago

I have come across a problem implementing a firebase-auth context in my app. All seemed well until I tried to handle persistence with firebase. As you can see below, firebase uses an observable called onAuthStateChanged to grab the logged in user, and this can be used to update an auth object to pass down via a provider. When you refresh that app, the observable will eventually return an auth object again, which should update the provider, and update all the components that consume the auth context in the react tree.

At first I get an error: TypeError: Cannot read property 'user' of undefined

If I log state within my consuming component, I get: Auth state within component undefined

This is my component that acts as a provider to the rest of the app component tree.

import React from "react";
import * as firebase from "firebase/app";
import { firebaseAuth } from "../reducers/AuthReducer";

export const Auth = React.createContext();

export const AuthProvider = (props) => {
  const [state, dispatch] = React.useReducer(
    { user: {} },
    firebase.auth().onAuthStateChanged((user) => {
      return user;

  return (
    <Auth.Provider value={{ state, dispatch }}>{props.children}</Auth.Provider>

This is my component that consumes the provided auth context:

import React from "react";
import HomePageAuth from "./homepageauth/HomePageAuth";
import "./rightpanel.module.less";
import NavCluster from "../../../nav/navcluster/NavCluster";
import { Auth } from "../../../../contexts/AuthContext";

const RightPanel = () => {
  const { state, dispatch } = React.useContext(Auth);

  console.log("Auth state within component", state);

  return (
        display: "flex",
        justifyContent: "center",
        marginTop: "80px",
        width: "50%",
      {state.user ? <NavCluster /> : <HomePageAuth />}

export default RightPanel;