I was setting up a dashboard project with this tutorial : https://css-tricks.com/user-registration-authentication-firebase-react/
Everything is fine except when I'm reloading a page : I'm always back to the login page (because I'm disconnected)
I think it's an issue in this chunk of code in App.js :
function App() {
const [currentUser, setCurrentUser] = useState({})
const [timeActive, setTimeActive] = useState(false)
useEffect(() => {
onAuthStateChanged(auth, (user) => {
setCurrentUser(user)
})
}, [])
return (
<Router>
<AuthProvider value={{currentUser, timeActive, setTimeActive}}>
<Switch>
<PrivateRoute exact path="/" component={Profile} />
<Route exact path="/login" component={Login} />
<Route exact path="/register" component={Register} />
<Route exact path='/verify-email' component={VerifyEmail} />
</Switch>
</AuthProvider>
</Router>
);
}
export default App;
I did some console.log inside useEffect and the output shows the state "currentUser" is empty for a moment, which I think is the reason a refresh disconnects me.
Do anyone knows a fix for that ?
CodePudding user response:
Firebase APIs load auth state asynchronously so it can take a moment for it to load. You should use onAuthStateChanged()
whenever your website loads and if the user is not logged then redirect to login and vice versa. For exameple:
onAuthStateChanged(auth, (user) => {
if (user) {
// User present
setCurrentUser(user)
// redirect to home if user is on /login page
} else {
// User not logged in
// redirect to login if on a protected page
}
})