Last active
August 29, 2015 14:24
-
-
Save acdlite/1168dd2c3cbd8e4cb477 to your computer and use it in GitHub Desktop.
Potential redux-react-router API
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
function reactRouter(router) { | |
return (reducer, initialState) => next => { | |
const baseStore = next(reducer, initialState); | |
function storeIsInSyncWithRouter() { | |
//... blah blah implementation details | |
} | |
// Apply router middleware which intercepts TRANSITION_TO actions | |
const wrappedDispatch = routerMiddleware(router)()(baseStore.dispatch); | |
const store = { | |
...baseStore, | |
dispatch: (action) => { | |
wrappedDispatch(action); | |
// After dispatching, check if store state is out of sync with router | |
if (!storeIsInSyncWithRouter()) { | |
const { pathname, query, state } = baseStore.getState().router; | |
// Trigger transition in response to external state change | |
// E.g. Redux Devtools time travel | |
router.transitionTo(pathname, query, state); | |
} | |
return action; | |
} | |
}; | |
// Need some way to subscribe to transitions | |
// Different from History.addChangeListener because transitions may be | |
// aborted, redirected, async, etc. | |
router.subscribe((location, params, components) => { | |
// Triggers LOCATION_DID_CHANGE actions | |
// (probably should rename this to DID_TRANSITION_TO for clarity) | |
if (!storeIsInSyncWithRouter()) {} | |
baseStore.dispatch(locationDidChange(location, params)); | |
} | |
}); | |
return store; | |
}; | |
} | |
// Compose with other higher-order stores | |
const store = compose( | |
applyMiddleware(m1, m2, m3) | |
reactRouter(router), | |
devTools, | |
createStore | |
)(reducer, initialState); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment