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,
};
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
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} />