I'm trying to set up login-register routing for my web application.
The idea is:
Login and Register
If there is no authentication, it will direct to
/loginwhich will then render theLogincomponent. If there is, I will direct to/dashboard- In
Login, if the user types correct username and password, it will redirect to/dashboard, else it doesn't do anything regarding routing. - If the user visit
/If there is any authentication, the user will redirect to/dashboardelse to/login
I have tried to use this.props.history.push to redirect between the Login-DashBoard components.
Here are my routings so far, I don't know if this is best practice yet. If it is not, any bits of help would be appreciated.
Routing.js:
...
render() {
return(
<>
<Route path="/login"><Login showAlert={this.showAlert}/></Route>
<Route path="/register"><Register showAlert={this.showAlert}/></Route>
<AuthRoute authed={AuthenticationService.isUserLoggedIn()} path="/">
<Dashboard/>
</AuthRoute>
<AuthRoute authed={AuthenticationService.isUserLoggedIn()} path="/dashboard">
<Dashboard/>
</AuthRoute>
</>
)
...
Login.js:
...
componentDidMount() {
if(AuthenticationService.isUserLoggedIn()) {
this.props.history.push('/dashboard');
}
}
...
handleSubmit = (event) => {
event.preventDefault();
AuthenticationService.authenticateAccount(this.state.email, this.state.password)
.then(() => {
this.props.history.push('/dashboard')
});
}
...
export default withRouter(Login);
However, it has Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops. although I use componentDidMount()
Again, any help would be appreciated.
Thanks.
UPDATE:
The problem only happens after clicking login from /login
