Home > Blockchain >  React Context API doesn't work when passing null
React Context API doesn't work when passing null

Time:02-15

I'm setting up auth for a React/Firebase app, and I want the user's logged in/off status to be global, so I can conditionally render certain elements (in any component) based on that status.
I pulled the current user status from firebase and set it as context, as follows:

FirebaseContext.js

import { auth } from "./firebaseConfig";
import { createContext } from "react";

export const FirebaseContext = createContext()

const user = auth.currentUser 


const FirebaseContextProvider = (props) => {
        return(
            <FirebaseContext.Provider value = {user}>
                {props.children}
            </FirebaseContext.Provider>
        )
}

export default FirebaseContextProvider

The problem is this - when the user's status is logged off, the user value being passed down is null. This makes my app crash when I try to destructure the user property in whichever component I'm using context:

Uncaught TypeError: Cannot destructure property 'user' of '(0 , react__WEBPACK_IMPORTED_MODULE_0__.useContext)(...)' as it is null.

...and here's the first part of the header component where I'm using context:

import { useContext, useRef } from 'react'
import { FirebaseContext } from '../FirebaseContext';
import { Link } from 'react-router-dom'
import { getAuth, signOut } from "firebase/auth";

const Header = () => {

const { user } = useContext(FirebaseContext)

...and how I've set up my app

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Landing from './pages/landing'
import Venue from './pages/venues'
import SignUp from './pages/sign-up';
import Login from './pages/login';
import FirebaseContextProvider  from './FirebaseContext'
import './styles.css';

function App() {
  return (
  <FirebaseContextProvider>
    <Router>
      <div>
        <Routes>
          <Route path = '/' exact element = {<Landing />} />
          <Route path = '/venue/:id' element = {<Venue/>}/>
          <Route path = '/signup' element = {<SignUp/>}/>
          <Route path = '/login' element = {<Login/>}/>
        </Routes>
      </div>
    </Router>
  </FirebaseContextProvider>
  );
}

export default App;

I tried setting up a conditional in FirebaseContext.js to overcome this problem, to return a string that I would use to conditionally render elements:
const activeUser = user ? user : 'no active user',but this didn't help as it returned undefined. Any suggestions?

CodePudding user response:

The value of the context provider is to be an object. To avoid this issue when a null is passed in, try doing so instead :

const FirebaseContextProvider = (props) => {
        return(
            <FirebaseContext.Provider value = {{user}}>
                {props.children}
            </FirebaseContext.Provider>
        )
}
  • Related