I would like to make use of react-router's onEnter
handler in order to prompt users to authenticate when entering a restricted route.
So far my routes.js
file looks something like this:
import React from 'react';
import { Route, IndexRoute } from 'react-router';
export default (
<Route path="/" component={App}>
<IndexRoute component={Landing} />
<Route path="learn" component={Learn} />
<Route path="about" component={About} />
<Route path="downloads" component={Downloads} onEnter={requireAuth} />
</Route>
)
Ideally, I'd like my requireAuth
function to be a redux action that has access to the store and current state, that works like this: store.dispatch(requireAuth())
.
Unfortunately I don't have access to the store in this file. I don't think I can use really use connect
in this case to access the relevant actions that I want. I also can't just import store
from the file where the store is created, as this is undefined when the app first loads.
If you want that you could write route.js like this:
I've setup an example which you could play with in this codepen.
Not sure if triggering an action in order to handle the auth is a good idea. Personally I prefer handling auth in a different way:
Instead of using an
onEnter
hook, I use a wrapping function. I want the admin section of my blog protected, therefore I wrapped theAdminContainer
component in the routes with a function,requireAuthentication
, see below.requireAuthentication
is a function thatLogin
You can see it below:
Also,
requireAuthentication
will protect all routes under/admin
. And you can reuse it wherever you like.Lots have changed over the time.
onEnter
no longer exists onreact-router-4
The following is from my real project for your reference
The easiest way to accomplish this is to pass your store to a function that returns your routes (rather than return your routes directly). This way you can access the store in
onEnter
and other react router methods.So for your routes:
Then update your main component to call the
getRoutes
function, passing in the store:As for dispatching an action from
requireAuth
, you could write your function like this:Hope this helps.