Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

245
Views
How to stop already logged in user to go back to the sign-in page in React.js

Here, I'm trying to stop the user to go back to the login page if the user is currently signed in, the first line in the render function is causing an error

Error: 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.

But I'm not calling setState here, I'm just calling a function from another module to check if it returns a user or not

render() {
if (auth.getCurrentUser()) return <Redirect to="/" />;

return (
  <div id="loginWrapper">
    <h3>Login</h3>
    <ToastContainer />
    <form onSubmit={this.handleSubmit}>
      {this.renderInput("username", "Username")}
      {this.renderInput("password", "Password", "password")}
      {this.renderButton("Login")}
    </form>
  </div>
);

}

and here is my auth module from where the function is being called,

    import jwtDecode from "jwt-decode";

export function getCurrentUser() {
  try {
    const jwt = localStorage.getItem("token");
    return jwtDecode(jwt);
  } catch {
    return null;
  }
}

   
export default {
  getCurrentUser,
};
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

use ternary condition with jwt token on your route which may help you to check the user is logged in or not also you can make your route private. ty

about 4 years ago · Juan Pablo Isaza Report

0

You could create a ProtectedRoute component that redirects based on auth status.

import React from 'react';
import { Route } from 'react-router-dom';

const ProtectedRoute = ({ component: Component, ...restProps }) => {
  return (
    <Route {...restProps} render={
      props => {
        if (!auth.getCurrentUser()) {
          return <Component {...rest} {...props} />
        } else {
          return <Redirect to={
            {
              pathname: '/',
              state: {
                from: props.location
              }
            }
          } />
        }
      }
    } />
  )
}

export default ProtectedRoute;

You can then call the ProtectedRoute component on the login page thus:

<ProtectedRoute path='/login' component={LoginPage} />
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!