Every time the page is refreshed the user is sent back to the login screen after authentication. I am using the onAuthStateChanged listener, however, after the page is refreshed it acts like there was no authenticated user to begin with.
const dispatch = useDispatch();
const currentUser = useSelector((state) => state.user.value);
useEffect(() => {
auth.onAuthStateChanged((user) => {
if (user) {
dispatch(setCurrentUser({ email: user.email, uid: user.uid }));
console.log("user", user.email);
}
});
}, []);
return currentUser.email ? <LoggedIn /> : <Welcome />;
}
CodePudding user response:
const dispatch = useDispatch();
const currentUser = useSelector((state) => state.user.value);
useEffect(() => {
auth.onAuthStateChanged((user) => {
if (user) {
dispatch(setCurrentUser({ email: user.email, uid: user.uid }));
console.log("user", user.email);
}
});
}, [currentUser]);
return currentUser?.email ? <LoggedIn /> : <Welcome />;
}
maybe, that would help. just add currentUser to the second argument array
CodePudding user response:
I know that onAuthStateChanges() method is asynchronus. So just move rediraction inside this method.
const dispatch = useDispatch();
const currentUser = useSelector((state) => state.user.value);
useEffect(() => {
auth.onAuthStateChanged((user) => {
if (user) {
dispatch(setCurrentUser({ email: user.email, uid: user.uid }));
console.log("user", user.email);
openRoute(<LoggedIn />)
return
}
openRoute(<Welcome />)
});
}, []);
}
This function triggers whenever auth state changes so if you log out you wanna back to login page and this way will work.
