Skip to content

Instantly share code, notes, and snippets.

@poberwong
Last active December 25, 2019 20:27
Show Gist options
  • Save poberwong/2519c93520693744c3fe68bc6d75873f to your computer and use it in GitHub Desktop.
Save poberwong/2519c93520693744c3fe68bc6d75873f to your computer and use it in GitHub Desktop.
source code for applyMiddleware of redux
/* v3.5.2*/
export default function (...middlewares) {
return (createStore) => (reducers, initialState, enhancer) => {
const store = createStore(reducers, initialState, enhancer)
const dispatch = store.dispatch
const chain = []
const middleWareAPI = {
getState: store.getState,
dispatch: action => dispatch(action)
}
chain = middlewares.map(middleware => middleware(middlewareAPI))
dispatch = compose(...chain)(store.dispatch) // store.dispatch or dispatch both work
// compose will do following thing:
/*
* a, b, c ==> a(b(c())), indeed, it is just a reduce and store.dispatch will be an initial value
*/
return {
...store,
dispatch
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment