So I was following this Firebase in React Course, it was going great until I ran into an error even though I'm following the instructor.
I have this useSign()
hook:
which I use in this SignIn.jsx
Component:
import { useEffect, useState } from "react";
import { useAuth } from "./useAuth";
import { auth } from "../firebase/config";
export default function useSignin() {
const [unmounted, setUnmounted] = useState(false);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const { dispatch } = useAuth();
const signIn = async (email, password) => {
setLoading(true);
setError(null);
console.log("inside signin, unmounted: ", unmounted);
try {
console.log("inside try, unmounted: ", unmounted);
const res = await auth.signInWithEmailAndPassword(email, password);
console.log("inside try after signin, unmounted: ", unmounted);
dispatch({
type: "LOGIN",
payload: res.user,
});
console.log("inside try after dispatch, unmounted: ", unmounted);
if(!unmounted) {
setLoading(false);
setError(null);
}
} catch (err) {
console.log("inside catch, unmounted: ", unmounted);
if (!unmounted) {
setError(err.message);
setLoading(false);
};
}
};
useEffect(() => {
return () => setUnmounted(true);
}, []);
return { signIn, error, loading };
}
`export default function SignIn() {
const {signIn, loading, error} = useSignin();
const handleSubmit = (e) => {
e.preventDefault();
console.log("signing in...")
signIn(e.target.email.value, e.target.password.value);
}
return (
<form onSubmit={handleSubmit} className={styles["signIn"]}>
<h2>Login</h2>
<div>
<label htmlFor="email">Email</label>
<input type="email" name="email" id="email" />
</div>
<div>
<label htmlFor="password">Password</label>
<input type="password" name="password" id="password" />
</div>
{!loading && <button type="submit">Sign in</button>}
{loading && <button type="submit" disabled>Signing in...</button>}
{error && <p>{error}</p>}
</form>
);
}
The problem is, that the "empty-arrayed" useEffect in the hook is triggering twice with the cleanup function being triggered in between? setting unmounted
to true and preventing loading
and error
to set states, all of that while the component is still mounted. Mind you, the Instructor's code looks exactly the same as far as I can tell..
would appreciate some help.. Thanks!
I couldn't figure out a solution, all I did was debug with some console logs and apparently the problem lies in the cleanup function being triggered when the component renders..