Search code examples
javascriptfirebasenext.js

i made a context to show the email after logging in (next js and firebase) but an error appeared when i try to show the email in navbar


this error appears when i try to load the page

Error: (0 , lib_AuthContext__WEBPACK_IMPORTED_MODULE_1_.useAuth) is not a function

btw the sign in and signup works

AuthContext.js

"use client";

import { createContext, useContext, useEffect, useState } from "react";
import { onAuthStateChanged, getAuth } from "firebase/auth";
import { auth } from "./firebase";

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (user) => {
      setUser(user);
    });

    return () => unsubscribe();
  }, []);

  return (
    <AuthContext.Provider value={{ user }}>{children}</AuthContext.Provider>
  );
};

export const useAuth = () => useContext(AuthContext);

Navbar.jsx

const { user } = useAuth();
{user ? (
          <span className="navbar-user-email">{user.email}</span>
        ) : (
          <>
            <Link href="/auth/login" className="navbar-link">
              Login
            </Link>
            <Link href="/auth/signup" className="navbar-link">
              Sign Up
            </Link>
          </>
        )}

i tried doing everything but nothing works


Solution

  • This may be cause you are nesting the useContext in unnecessary function calls

    Instead of doing:

    export const useAuth = () => useContext(AuthContext);
    

    in AuthContext.js

    you should just do that within Navbar.jsx

    import {AuthContext} from "./AuthContext"
    
    
    const { user } = useContext(AuthContext);
    {user ? (
              <span className="navbar-user-email">{user.email}</span>
            ) : (
              <>
                <Link href="/auth/login" className="navbar-link">
                  Login
                </Link>
                <Link href="/auth/signup" className="navbar-link">
                  Sign Up
                </Link>
              </>
            )}