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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With