Skip to content

Instantly share code, notes, and snippets.

@goatslacker
Last active June 20, 2017 03:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goatslacker/e21539784342c63f22c030ee1e600cac to your computer and use it in GitHub Desktop.
Save goatslacker/e21539784342c63f22c030ee1e600cac to your computer and use it in GitHub Desktop.
import { createStore, compose, applyMiddleware } from 'redux'
export default function createInjectableStore(reducers, preloadedState, enhancer) {
const injectedMiddleware = []
const injectableMiddleware = store => next => action => {
const chain = injectedMiddleware.map(m => m(store))
const dispatchThroughMiddleware = chain.reduceRight((next, f) => {
return f(next)
}, action => next(action))
return dispatchThroughMiddleware(action)
}
function injectMiddleware(middleware) {
injectedMiddleware.push(store => next => action => {
return middleware(store)(next)(action)
})
}
const store = createStore(
reducers,
preloadedState,
compose(enhancer, applyMiddleware(injectableMiddleware))
)
return Object.assign(store, {
injectMiddleware,
})
}
@goatslacker
Copy link
Author

goatslacker commented Jun 17, 2017

Usage:

const store = createInjectableStore(reducers, preloadedState, applyMiddleware(thunk))

store.injectMiddleware(todoMiddleware)

@goatslacker
Copy link
Author

Updated gist which scopes the injected middleware into "local" middleware. https://gist.github.com/goatslacker/511a92a4fa154ad4dc9e6b844da6b310

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment