0

So I was playing arround with onAuthStateChanged listeners, reading the firebase docs, the current user also can be gotten using auth.currentUser (in useEffect), when the Context provider mounts. Althought there is a user logged in, auth.currentUser returned null. Is there a problem with the code?

const Component= () => {
const { currentUser, setCurrentUser } = useContext(UserContext);
const getCurrentUser = () => {
const auth = getAuth();
const user = auth.currentUser;
return user;
}
   useEffect(() => { 
        const user = getCurrentUser();
        if(user){
            setCurrentUser(prevUser => user);
        }
        else setCurrentUser(prevUser => null);
            
    }, [currentUser])
    return (
        <UserContext.Provider value={{ currentUser, setCurrentUser }}>
            {children}
        </UserContext.Provider>
    )
}

onAuthStateChanged will return the current active user, but auth.currentUser returned null .

  • `auth.currentUser` will be `null` until the first `onAuthStateChanged` event fires. This is a limitation with Firebase where it needs to initialise auth on page load – Phil Feb 09 '23 at 00:53
  • See this 5 year old unresolved issue if you feel like banging your head against a brick wall ~ https://github.com/firebase/firebase-js-sdk/issues/462 – Phil Feb 09 '23 at 00:54

0 Answers0