How do I know when auth.currentUser is readable? #6811
Replies: 2 comments 1 reply
-
Use |
Beta Was this translation helpful? Give feedback.
0 replies
-
Use onAuthStateChanged with conditional redirection logic.
const [isAuthChecked, setIsAuthChecked] = useState(false);
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(user => {
setIsAuthChecked(true);
// Your redirect logic here
});
return () => unsubscribe();
}, []);
if (isAuthChecked && !auth.currentUser) {
// Redirect to login
} Context: onAuthStateChanged runs immediately upon attaching, indicating the initial auth state. Using a flag like isAuthChecked helps differentiate between 'not checked' and 'not logged in'. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have some redirections in place so that the user is sent to the /login page if they are not logged in. Unfortunately, at least when using the auth emulator,
auth.currentUser
isnull
for a moment and then becomes populated. So I end up redirecting to login, then back once it finally initializes.Is there a good way to wait for the state of
auth.currentUser
to be ready for reading? I don't think I can wait foronAuthStateChanged
since if the user really is logged out, I really do want to redirect them immediately.Thanks!
Beta Was this translation helpful? Give feedback.
All reactions