Maximum update depth exceeded with this.props.history.push

Viewed 2011

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 /login which will then render the Login component. 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 /dashboard else 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()

enter image description here

Again, any help would be appreciated.

Thanks.

UPDATE: The problem only happens after clicking login from /login

1 Answers

I was able to escape this loop by comparing the router location to the push that I was trying to make, like so:

import { withRouter, useHistory, useLocation } from 'react-router-dom';

//...

const App = () =>  {

    //...

    const history = useHistory();

    const location = useLocation();

    const changePage = (change: { page: string, params: string, refresh: boolean}) => {

        if (location.pathname !== change.page || location.search !== change.param) {
     
            history.push({
                pathname: change.page,
                search: change.param
            });

        };

        if (change.refresh) {
            history.go(0);
        };

    };

    //...

};

export default withRouter(App);

Related