Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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",
like image 239
Josh Avatar asked Nov 02 '15 22:11

Josh


2 Answers

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>
        );
like image 73
ganmor Avatar answered Nov 07 '22 23:11

ganmor


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()

like image 4
Peter Kowalczyk Avatar answered Nov 07 '22 22:11

Peter Kowalczyk