Reputation: 171
I am looking for help with my react router onEnter prop. Seems like that onEnter prop is triggered on every component in my app, event though I am not specifying that. Pretty sure it is something related with my router setup.
My code:
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route
path="/1"
components={{ main: Hierarchy, sidebar: NavBar }}
onEnter={AWSApi.tokenIsValid(authHeader)}
/>
<Route
path="/2"
components={{ main: Entities, sidebar: NavBar }}
onEnter={AWSApi.tokenIsValid(authHeader)}
/>
<Route
path="/2/:id"
component={Analysis}
onEnter={AWSApi.tokenIsValid(authHeader)}
/>
<Route path="/1/:id" component={Entity} onEnter={AWSApi.tokenIsValid(authHeader)} />
</Route>
<Route path="/login" component={AuthForm} />
<Route path="/new-password" component={ChangePasswordForm} />
</Router>
Upvotes: 3
Views: 97
Reputation: 59511
Edit: Actually @bennygenel spotted the issue you're having with the authentication happening on every route. But there is another issue with your routing which I'll cover below:
You have an issue with the order in which you have defined your routes.
For example, if you visit /login
the route will satisfy <Route path="/" />
and enter that. Similarly, visiting /1/ABC
will satisfy <Route path="/1" />
and enter that. Generally, you should define the stricter/more specific routes first, then the more general ones.
You should define them like this:
<Router history={browserHistory}>
<Route path="/login" component={AuthForm} />
<Route path="/new-password" component={ChangePasswordForm} />
<Route path="/" component={App}>
<Route path="/1/:id" component={Entity} onEnter={() => AWSApi.tokenIsValid(authHeader)} />
<Route
path="/1"
components={{ main: Hierarchy, sidebar: NavBar }}
onEnter={() => AWSApi.tokenIsValid(authHeader)}
/>
<Route
path="/2/:id"
component={Analysis}
onEnter={() => AWSApi.tokenIsValid(authHeader)}
/>
<Route
path="/2"
components={{ main: Entities, sidebar: NavBar }}
onEnter={() => AWSApi.tokenIsValid(authHeader)}
/>
</Route>
</Router>
You should check out the Precedence section from the official docs:
Finally, the routing algorithm attempts to match routes in the order they are defined, top to bottom. So, when you have two sibling routes you should be sure the first doesn't match all possible
path
s that can be matched by the later sibling. For example, don't do this:<Route path="/comments" ... /> <Redirect from="/comments" ... />
Upvotes: 2
Reputation: 24660
Actually your problem is that you are executing the function rather then sending it as a prop.
This
onEnter={AWSApi.tokenIsValid(authHeader)}
should be
onEnter={() => AWSApi.tokenIsValid(authHeader)}
Upvotes: 1