This is my authContext.js file which runs on load of the website.
"use client";
import { createContext, useContext, useState, useEffect } from "react";
import { auth } from "../firebase";
import { onAuthStateChanged } from "firebase/auth";
const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
console.log("AuthProvider is rendering");
const unsubscribe = onAuthStateChanged(auth, (user) => {
console.log("Auth state changed in provider:", user);
setCurrentUser(user);
setLoading(false);
});
return () => unsubscribe();
}, []);
return (
<AuthContext.Provider value={{ currentUser, loading }}>
{children}
</AuthContext.Provider>
);
};
export function useAuth() {
return useContext(AuthContext);
}
When I try to login the navbar returns null for the current user. Here is the useEffect I have implemented in the navbar.
const { currentUser } = useAuth();
const [role, setRole] = useState(null);
useEffect(() => {
console.log('Current user in Navbar:', currentUser);
if (currentUser) {
const fetchUserRole = async () => {
const userDoc = await getDoc(doc(firestore, "users", user.uid));
if (userDoc.exists()) {
const userData = userDoc.data();
setRole(userData.role);
} else {
console.log("User document does not exist in Firestore.");
}
};
fetchUserRole();
} else {
setRole(null);
}
}, [currentUser]);
I also have an api folder for the route.js file that does the backend firebase calls to create new users and to get the current user. This is all inside a export async function POST(request)
// Sign In logic
const userCredential = await signInWithEmailAndPassword(
auth,
email,
password
);
const user = userCredential.user;
// Retrieve role from Firestore by querying both collections
let userRole = "unknown";
const userDoc = await getDoc(doc(firestore, "users", user.uid));
if (userDoc.exists()) {
userRole = userDoc.data().role;
} else {
const vendorDoc = await getDoc(doc(firestore, "vendors", user.uid));
if (vendorDoc.exists()) {
userRole = vendorDoc.data().role;
}
}
// Check if the user is an admin (You can have a flag like `isAdmin`)
const adminDoc = await getDoc(doc(firestore, "admins", user.uid));
if (adminDoc.exists()) {
userRole = "admin"; // If user is admin, override role
}
console.log("User Role:", userRole);
return new Response(
JSON.stringify({
message: `${userRole} signed in successfully`,
role: userRole,
}),
{ status: 200 }
);
I am expecting the user to stay logged in so that the navbar can render some user information when logged in but the user keeps returning null after logging in. I checked the paths and when the user logs in it returns the new Response saying the specific role signed in successfully but the console.log in the navbar says the user is null.