Reputation: 528
My React application, upon loading, checks to see if there's an authenticated user. If there is, then the authenticated user is redirected to their "Dashboard" page. When this happens, however, the application with briefly flicker/flash the non-authenticated landing page before the redirect. Is there a way to prevent this from happening?
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom'
import { SignUp } from './SignUp'
import { Login } from './Login'
import { Dashboard } from './Dashboard'
import { Welcome } from './Welcome.js'
import { AuthContextProvider, useAuthState } from './firebase'
const AuthenticatedRoute = ({ component: C, ...props }) => {
const { isAuthenticated } = useAuthState()
console.log(`AuthenticatedRoute: ${isAuthenticated}`)
return (
<Route
{...props}
render={routeProps =>
isAuthenticated ? <C {...routeProps} /> : <Redirect to="/welcome" />
}
/>
)
}
const UnauthenticatedRoute = ({ component: C, ...props }) => {
const { isAuthenticated } = useAuthState()
console.log(`UnauthenticatedRoute: ${isAuthenticated}`)
return (
<Route
{...props}
render={routeProps =>
!isAuthenticated ? <C {...routeProps} /> : <Redirect to="/" />
}
/>
)
}
function App() {
return (
<AuthContextProvider>
<Router>
<div></div>
<AuthenticatedRoute exact path="/" component={Dashboard} />
<UnauthenticatedRoute exact path="/signup" component={SignUp} />
<UnauthenticatedRoute exact path="/signin" component={Login} />
<UnauthenticatedRoute exact path="/welcome" component={Welcome} />
</Router>
</AuthContextProvider>
)
}
export default App
Upvotes: 2
Views: 1492
Reputation: 694
Daniel's answer explains the problem very well -- I have a few things to add though. Here is how you can get the loading status.
const [user, loading] = useAuthState(auth)
Then you can check for the loading status and return null. Hover this can create a white flash, because you're loading blank page for a second. I recommend loading the Navbar / header or footer instead of null.
Upvotes: 0
Reputation: 319
This is because while the firebase request is getting a response isAuthenticated is false.
You could use useAuthState isLoading flag to return null or an empty div before your actual return statement, so the first page loaded is blank.
if (isLoading) return null
// Then your actual return statement.
When isLoading turns false the isAuthenticated flag will resolve directly to the definitive value.
Try it and tell me if it works.
Upvotes: 3