Created
March 27, 2018 04:37
-
-
Save whs/35b69122d77f7ed3c4d337b6a300d00c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import transitionPath from 'router5-transition-path'; | |
| export const withStore = (router, dependencies) => async (toState, fromState) => { | |
| let stores = {}; | |
| if (fromState && fromState.stores) { | |
| stores = fromState.stores; | |
| } | |
| const { toActivate } = transitionPath(toState, fromState); | |
| let storePromises = []; | |
| for (let segment of toActivate) { | |
| let route = routesMap[segment]; | |
| if (!route || !route.store) { | |
| continue; | |
| } | |
| if (stores[route.storeName]) { | |
| let store = stores[route.storeName]; | |
| store.updateState(toState); | |
| } else { | |
| let promise = route.store(toState).then(Store => { | |
| Store = Store.__esModule ? Store.default : Store; | |
| let store = new Store({ router, ...dependencies }); | |
| store.updateState(toState); | |
| stores[route.storeName] = store; | |
| }); | |
| storePromises.push(promise); | |
| } | |
| } | |
| await Promise.all(storePromises); | |
| toState.stores = stores; | |
| return toState; | |
| }; | |
| // in routes | |
| const routes = [ | |
| { | |
| name: 'home', | |
| path: '/', | |
| component: Loadable({ loader: () => import(/* webpackChunkName: 'home' */ '../pages/home'), loading: Loading }), | |
| fetch: (state, { api }) => api.getHome(), | |
| store: () => import(/* webpackChunkName: 'home' */ '../pages/home/store'), | |
| storeName: 'home', | |
| } | |
| ] | |
| // in App | |
| // ... | |
| return ( | |
| <Provider {...route.stores}> | |
| <Component {...props} /> | |
| </Provider> | |
| ); | |
| // ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment