So have followed the answers in this question to do a router based on whether the user is authenticated or not.
My route looks like this (this is an Authentication only App)-
"/" -> Login
|
|
|- "/home" -> User Home page based on some criteria of the logged in user
|
|- "/catalog" -> Catalog page based on some criteria of the logged in user
In short, the /home
and /catalog
are protected routes and only authenticated users are allowed. All non authenticated users must be routed to root i.e. "/"
which is the login page. The authentication check function is Async so I have my index.js and App.js something like this-
index.js
import PrivateRoute from './App';
<BrowserRouter>
<div>
<Switch>
<PrivateRoute path="/home" component={Client}/>
<PrivateRoute path="/catalog" component={Catalog}/>
<PrivateRoute path="/" component={Landing}/>
</Switch>
</div>
</BrowserRouter>
App.js
class App extends Component {
state = {
loading: true,
isAuthenticated: false,
role: ''
};
componentDidMount() {
getUserSession((isValid,session,err) => {
if (isValid){
console.log('is Valid Session');
this.setState({
loading: false,
isAuthenticated: isValid,
});
}else if (err){
console.log('is InValid Session');
this.setState({
loading: false,
});
}
});
}
render() {
const { component: Component, ...rest } = this.props
console.log(this.props);
return (
<Route
{...rest}
render={props =>
this.state.isAuthenticated ? (
<Component {...props} />
) : (
this.state.loading ? (
<div>LOADING</div>
) : (
<Redirect to={{ pathname: '/', state: { from: this.props.location } }} />
)
)
}
/>
)
}
}
It's worth noting that I am not using Redux for grabbing the Authentication state of the user, instead using AWS Amplify method calls to simply get the user session. The getUserSession
function returns whether a user session is Valid and some additional information like the session object etc.
I have 2 issues -
When an un-authenticated user comes in, the redirect is causing an infinite loop since
"/"
goes through the authentication check again and again via theRedirect
causing anMaximum update depth exceeded
error because ofsetState
call in App.js.If a user is authenticated then they end up in the
<Component {...props} />
line in App.js. This is ok as long as the user is hitting the specific/home
or/catalog
routes. However, if the user is authenticated and hits the root route/
i would want them to re-direct them to one of either/home
or/catlog
routes and I am simply not getting how to do that.
Any insights would be greatly appreciated.