I'm working on an app utilizing firebase and nextjs. I've set up a login page, but when I try to retrieve the current user, it returns undefined. This issue began a few days ago while working in react native as well - initially, it was related to state management. After updating from Firebase version 9.2.0 to 10.0.0, the user's state is no longer being retained.
Next.js Code:
AuthConext.js:
import React from "react";
import { onAuthStateChanged, getAuth } from "firebase/auth";
import firebase_app from "@/firebase/config";
const auth = getAuth(firebase_app);
export const AuthContext = React.createContext({});
export const useAuthContext = () => React.useContext(AuthContext);
export const AuthContextProvider = ({ children }) => {
const [user, setUser] = React.useState(null);
const [loading, setLoading] = React.useState(true);
React.useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
if (user) {
console.log("user change");
setUser(user);
} else {
setUser(null);
}
setLoading(false);
});
return () => unsubscribe();
}, []);
return (
<AuthContext.Provider value={{ user }}>
{loading ? <div>Loading...</div> : children}
</AuthContext.Provider>
);
};
Login.js (Check comments) :
const { user } = useAuthContext(); // Retrieves Current User
async function handleSignIn() {
if (password && email) {
const { result, error } = await signIn(email, password); // signin with email function rest is handled in another file where the sign-in with Email Password function is called
console.log(user); // Returns undefined
if (error) {
setErrorStop(error);
} else {
router.push("/blog"); // Tried on /blog page too with the same AuthContext but still returned undefined
}
}
}
Some suggest that the user might be taking time to initialize. I tested it on a separate page, but it still returned undefined.