Home > Software engineering >  Firebase useAuth() context in App.js is undefined?
Firebase useAuth() context in App.js is undefined?

Time:09-30

I have a AuthProvider and useAuth method that returns useContext(AuthContext) inside my App.js root file, however, if I console.log the return value of useAuth() in App.js, it is undefined, why?? In any other child component like Loginpage, there is an authContext displayed..

my App.js:

import { AuthProvider, useAuth } from './providers/AuthProvider'
function App() {
    const auth = useAuth()
    console.log({ auth }) //undefined??

AuthProvider.js:

import React, { useContext, useState, useEffect } from 'react'
import { app, auth, firestore, storage } from '../firebase'

const AuthContext = React.createContext()

export function useAuth() {
    return useContext(AuthContext)
}
export function AuthProvider({ children }) {
    const [currentUser, setCurrentUser] = useState(undefined)
    const [loginError, setLoginError] = useState(null)

    const login = async (email, password) => {
        try {
            return auth.signInWithEmailAndPassword(email, password)
        } catch (error) {
            setLoginError(error)
        }
    }

    

    const logout = () => auth.signOut()

    useEffect(() => {
        const unsubscribe = auth.onAuthStateChanged(user => {
            setCurrentUser(user)
        })
        return unsubscribe
    }, [])

    const value = {
        loginError,
        login,
        signup,
        logout,
        currentUser,
        app,
        firestore,
        storage,
        auth,
    }

    return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}

CodePudding user response:

Since you import AuthProvider in same file of App it gives a clue that you didn't use the Context API correctly.

Context values are available for Context-Consumers.

Context-Consumers are children of Context-Provider, therefore your App component have to be a child of <AuthContext.Provider>:

<AuthProvider>
  <App />
</AuthProvider>
  • Related