Reputation: 1161
I'm creating a simple react web app with token authentication. Everything is working fine except when I define a private route and the user is authenticated the private route is not being returned.
App.js
const App = () => {
return(
<AuthState>
<AlertState>
<Router>
<Fragment>
<Alerts />
<Switch>
<Route path="/" exact={true} component={Login} />
<PrivateRoute exact path='/admin' component={Admin} />
</Switch>
</Fragment>
</Router>
</AlertState>
</AuthState>
);
};
And this is my privateRoute.js:
const PrivateRoute = ({ component: Component, ...rest }) => {
const authContext = useContext(AuthContext);
const { isAuthenticated } = authContext;
// isAuthenticated is returning true at this point, but below is not returning my /admin
// path
return (
<Route {...rest} render={props => !isAuthenticated ? (
<Redirect to='/' />
) : (
<Component {...props} />
)} />
);
};
When the user is authenticated is /admin path should be called automatically, but nothing is happening. If I'm logged in, then if I manually enter the url path /admin, then I can see it's content.
Upvotes: 0
Views: 343
Reputation: 1558
Both of the comments are correct. The reason it's not redirecting you is because the login route definition comes before the other definition. Although the PrivateRoute component updates (since the context updates), the path is still "/", so it will not change. You have to manually navigate after you login to "/admin". Or you can create another component that wraps the Login component, which acts similarly to PrivateRoute, except if the user is logged in, then it routes them away from the Login page.
Upvotes: 2