'I'm getting this "Maximum update depth exceeded." while trying to handle firebase authentication error with useEffect
I'm using react firebase hooks library for firebase authentication. I'm trying to handle signInWithEmailAndPassword error using useEffect but getting this infinite error. "Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render."
const [signInWithEmailAndPassword, user, loading, error] =
useSignInWithEmailAndPassword(auth);
const [info, setInfo] = useState({
email: "",
password: "",
});
const [errors, setError] = useState({
email: "",
password: "",
});
const handleLogin = async (e) => {
e.preventDefault();
signInWithEmailAndPassword(info.email, info.password);
};
useEffect(() => {
if (error) {
switch (error?.code) {
case "auth/user-not-found":
setError({
...errors,
email: "No user found using that email",
});
setInfo({ ...info, email: "" });
break;
case "auth/wrong-password":
setError({ ...errors, password: "Wrong password" });
setInfo({ ...info, email: "" });
break;
default:
toast.error("Something went wrong");
break;
}
}
}, [error, errors, info]);```
Solution 1:[1]
The problem is that the useEffect will re-run whenever errors or info changes due to it depending on it: [error, errors, info]. So you will run into an infinite loop when you set setErrors or setInfo in there.
In this case the fix is quite simple - if you use the function callback version of setErrors/setInfo it will pass you errors/info without needing to pull it in as a dependency:
useEffect(() => {
if (error) {
switch (error?.code) {
case "auth/user-not-found":
setErrors(errors => ({
...errors,
email: "No user found using that email",
}));
setInfo(info => ({ ...info, email: "" }));
break;
case "auth/wrong-password":
setErrors(errors => ({ ...errors, password: "Wrong password" }));
setInfo(info => ({ ...info, email: "" }));
break;
default:
toast.error("Something went wrong");
break;
}
}
}, [error]);
(Note I renamed from setError to setErrors as I found it confusing since the variable is called errors (plural))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
