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",
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>
);
You might create file store.js and export final store (the same you pass to redux)
E.g.
import configureStore from 'utils/configure-store.js';
const store = configureStore();
export default store;
and then import to your router file and read state by store.getState()
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