Instead of useHistory I am trying to use navigate. But it's always showing me React Hook useEffect has missing dependencies: 'navigate' and 'setUser'. Either include them or remove the dependency array
useEffect(() => {
auth.onAuthStateChanged(async (user) => {
if(user) {
setUser(user);
navigate('/home');
}
})
}, [userName,setUser, navigate]);
const handleAuth = () => {
auth.signInWithPopup(provider).then((result) => {
setUser(result.user);
}).catch((error) => {
alert(error.message);
})
}
const setUser = (user) => (
dispatch(setUserLoginDetails({
name: user.displayName,
email: user.email,
photo: user.photoURL,
}))
)
Any help will be appreciated.
CodePudding user response:
How to fix missing dependency warning when using useEffect React Hook explains it better then I could.
You should also return a cleanup function at the end of useEffect
CodePudding user response:
According to convention, you have to include everything that you are using inside useEffect as a dependency, so if any of the dependency changes it'll trigger a re-render. In your case, you are using setUser and navigate
setUser(user);
navigate('/home');
So to avoid the warning add them to the dependency array, and since the navigate function is defined by react their address won't change no matter how many times the component re-renders but since setUser is defined by you, it has to be wrapped with useCallback so that the function doesn't get re-defined every time the component re-renders and trigger the useEffect.
So change your code too,
const setUser = useCallback( (user) => (
dispatch(setUserLoginDetails({
name: user.displayName,
email: user.email,
photo: user.photoURL,
}))
), [])
auth.onAuthStateChanged((user) => {
if(user) {
setUser(user);
navigate('/home');
}
})
}, [userName, setUser, navigate]);
And you should never declare your callback function as async, because if you do so you won't be able to return a cleanup function
So if your useEffect code should look something like this
useEffect(() => {
const user = async () => {}
user.then().catch() // if you want to change the state or show error message
return () => {} // you can also return a cleanup function if you are using timeout or intervals and want to clear the previous timeout or intervals
}, [dependencies])