Hey guys I am trying to use Firebase Authentication in my React App and I am doing this by setting up an context. I have checked a lot of questions regarding this and I wasn't able to get a satisfactory answer and so I am asking this here. Everything works except for the signInWithEmailAndPassword .My logic is that when the user signs in and the user has verified its email then take him to another page. Here in the context whenever the user object changes the onAuthStateChanged gets trigger and there I am updating the user object.But then to make this sign in work I have to click on the sign in button twice and then the page gets redirected. When the sign in button is triggered the first time , the setUser() doesnt update the user object quickly.
Here is the snippet of code for the context I have set up
const userAuthContext = createContext();
//Use the created context
export function useUserAuth() {
return useContext(userAuthContext);
}
export function UserAuthContextProvider({ children }) {
const [user, setUser] = useState({});
const [loading, setLoading] = useState(true);
// Sign in a user with email and password
function logIn(email, password) {
return signInWithEmailAndPassword(auth, email, password);
}
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
console.log(currentUser);
setUser(currentUser);
setLoading(false);
console.log("User is " , user);
});
const value = {
user,
logIn,
}
return (
<userAuthContext.Provider
value={value}
>
{!loading && children}
</userAuthContext.Provider>
);
}
And this is the login.js where I check that if the user has verified its email then I redirect to another page
export default function LoginForm() {
const { register, setError ,formState, handleSubmit } = useForm();
const { user, logIn } = useUserAuth();
const onSubmit = async(data) => {
console.log(data);
try{
await logIn(data.email,data.password);
}catch (error) {
setError("email", {
type: "manual",
message: error.message,
});
}
console.log(user);
if(user && user.emailVerified===true)
{
navigate('/studDash');
}else if(user){
setError("email", {
type: "manual",
message: "Email Not Verified !! Check your mail for verification mail !!",
});
}
}
return (
<div>
//Login Page Div is here
</div>
);
}
I have tried to do console.log(user) at onAuthStateChanged in the context and in the onSubmit function here is the screenshot of it. This is the console when I click the sign in button once , if i click signin button again then the user gets directed to next page successfully.