After clicking on submit I got this warning
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
This is the code
const handleSubmit = async (e) => { e.preventDefault()
let source = axios.CancelToken.source();
dispatch(login(email, password, source.token))
.then(() => {
console.log("Result from dispatch");
props.history.push("/Dashboard");//this is line which casues a warning.
window.location.reload();
})
.catch(() => {
setLoading(false);
});
}
How to avoid this warning? Any help would be appreciated.
CodePudding user response:
When props.history.push('/Dashboard')
is executed, your component gets unmounted, anything after you are trying to execute on this component (like a state update) would cause a memory leak.
CodePudding user response:
I solved the warning by adding this variable mounded inside useEffect. And I'm checking if a component is unmounted.
const mounted = useRef(false);
useEffect(() => {
mounted.current = true;
return () => { mounted.current = false; };
}, []);
const handleSubmit = async (e) => {
e.preventDefault()
let source = axios.CancelToken.source();
dispatch(login(email, password, source.token))
.then(() => {
if (!mounted) {
console.log("Result from dispatch");
props.history.push("/Dashboard");
window.location.reload();
}
})
.catch(() => {
setLoading(false);
});
}