Josh Josh -4 years ago 210
React JSX Question

How to connect to redux store from react-router onEnter hook?

I'd like to use react-router's

onEnter
hook to check a variable in my redux store when the route loads.

According to the docs,
onEnter
:


...receives the next router state as its first argument. The
replaceState
function may be used to trigger a transition to a different URL.


No store passed. Is it possible to connect to the redux store from within this hook? I've tried all sorts of things but cannot find a way to achieve this.

Versions I'm using:

"react-redux": "^4.0.0",
"react-router": "1.0.0-rc1",
"redux": "^3.0.0",

Answer Source

Make you routes a function that takes the store in parameter

export default (store) => {
 return (
  <Route handler={App} path="/">
    <Route path="mypath" component={handler} onEnter={myHook(store)}>
  <Route>
 )
};

Do the same in your transition hook

export const myHook = (store) => {
  return (location, replaceWith) => {
    // Do something with your store
  }
};

Then assuming your create your store and your router in the same file

const router = (
            <Provider store={store}>
                <Router history={history}>
                    {routes(store)}
                </Router>
            </Provider>
        );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download