Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router Cannot Get / depending on onEnter function

I am new to React and hoping someone can shed some light on why this is happening and how to debug it.

I have the following routes defined:

export default (withHistory, onUpdate) => {
  const history = withHistory?
              (Modernizr.history ?
                new BrowserHistory
              : new HashHistory)
            : null;
  return (
    <Router history={history}>
      <Route path='/login' component={Login} />
      <Route path='/' component={Home} onEnter={requireAuth} />
    </Router>
  );
};

requireAuth is supposed to check if the user is logged in and redirect them to the login page if not:

function requireAuth(nextState, transition) {
  transition.to("/login");
}

If I leave the transtion.to call in and browse to the root URL I just see a message that says, "Cannot Get /" with no error messages in the debugger. Putting a breakpoint on that line doesn't seem to do anything.

What's especially odd is that if I replace transition.to(...) with a debugger; statement, then the method is called and routing works perfectly fine.

I must have a misunderstanding on something, any ideas on what that is?

Edit: I should add that navigating to host:port/login works fine, so I know the login route works.

like image 276
shieldstroy Avatar asked Feb 08 '16 02:02

shieldstroy


1 Answers

Coming from an Angular background I had incorrectly assumed that routing was happening entirely client-side. It's possible to use react-router for both client-side and server side routing.

The transition.to call worked fine on the client-side, but threw an exception when server-side routing kicked in and returned the Cannot GET / page. The exception was being caught but nothing logged.

I added an if statement to see if we were running on the client:

if(window.location) {
    if(!loggedIn) {
        transition.to("/login");
    }
 }

There is probably a better way to handle this and if I figure that out eventually I'll update my answer.

like image 135
shieldstroy Avatar answered Nov 19 '22 09:11

shieldstroy