When the page loads, Firebase starts restoring the signed in user from the local storage of your browser. This requires a call to the server (a.o. to see if the account has been deleted/disabled), which takes some time.
So initially your onAuthStateChanged
gets called with null
as there is no current user. Then when the authentication state is restored the listener gets called again with the user profile.
My guess it that you're taking some action in the initial null
(like redirecting to index.html
), and that target page then redirect back to dashboard.html
when it gets the user profile.
It's easiest to work with Firebase in a single-page application, as you'd have only a single page load in that case. But if you have multiple pages, you'll need to write code that waits for the authentication state to settle.
Some common ways that I know of:
- Ignore the initial
null
that your onAuthStateChanged
callback gets. But keep in mind that the user state may not be restorable in which case the null
is all you get, so you may need to act on that after a while.
- Design your flow so that you end up in the right spot. This may only work in a single-page application, but I use this one most often: when the page loads (and the user is
null
), I show a log-in screen. Then when the user profile is restored I navigate to the dashboard. This means that users may briefly see the login screen, but I don't find this too distracting. If you do, read on...
- You can store a value in local storage yourself when the user is signed in. Then on a page reload, you can check that value and if it exists: assume that the restore of their auth state will succeed, and show the dashboard first. If the sign-in fails, you can then redirect back to the login screen after a timeout. So this inverts the path of #2, and requires quite some work, but removes the temporary login screen for your returning users.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…