Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router v4 - How to prevent redirect loops?

What I'm trying to accomplish is to have my App component redirect to the "/login" route if the state's uid is null. The redirect works correctly and will always redirect you to "/login" if there is a null uid, however the problem is it doesn't stop redirecting once you're on the "/login" route.

The error being thrown is:

Warning: You tried to redirect to the same route you're currently on: "/login"

One last constraint is I need the uid to be null until after a login event fires from the LoginScreen component. So the user needs to be able to view the "/login" route with a null uid in the top-level App component.

My code is as follows:

class App extends Component {
  constructor() {
    super();
    this.state = {
      uid: null
    }
  }
  render() {
    // Redirect to login if no user
    if (this.state.uid == null) {
      return (
        <Router>
          <Redirect to="/login" />
        </Router>
      );
    }

    return (
      <Router>
        <div>
          <Route path="/login" component={LoginScreen} />
          <Route path="/dashboard" component={DashboardScreen} />
          <Route path="/profile" component={ProfileScreen} />
        </div>
      </Router>
    );
  }
}

I hope I explained the situation well. Thanks in advance!

like image 804
saricden Avatar asked Nov 14 '25 22:11

saricden


2 Answers

Well as you mention that you have store the uid in the App component state and you are redirecting to the Login component if the uid is not present. However there is a technical fault here.

The state of the component is initilised everytime the component is mounted again and when you redirect from the Login component to the App component, your state in App component is again initialized to null which is why you are redirected again to Login.

What you need to do is to

Either store the uid in localStorage and read it from there in the App component

Or if you are using Redux, then store the uid in global store and fetch it in the App component.

like image 149
Shubham Khatri Avatar answered Nov 17 '25 22:11

Shubham Khatri


Its because when it redirects to /login it goes from '/' i.e App component and render function calls again which indeed redirects to /login and goes in the loop so on. So instead to prevent this update the state in login component and pass it to the parent component.

So if you are not using any store like redux, just set the state in the window.localStorage.

like image 27
Sambhav Jain Avatar answered Nov 17 '25 21:11

Sambhav Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!