UNPKG

1.24 kBJavaScriptView Raw
1import compose from './compose'
2
3/**
4 * Creates a store enhancer that applies middleware to the dispatch method
5 * of the Redux store. This is handy for a variety of tasks, such as expressing
6 * asynchronous actions in a concise manner, or logging every action payload.
7 *
8 * See `redux-thunk` package as an example of the Redux middleware.
9 *
10 * Because middleware is potentially asynchronous, this should be the first
11 * store enhancer in the composition chain.
12 *
13 * Note that each middleware will be given the `dispatch` and `getState` functions
14 * as named arguments.
15 *
16 * @param {...Function} middlewares The middleware chain to be applied.
17 * @returns {Function} A store enhancer applying the middleware.
18 */
19export default function applyMiddleware(...middlewares) {
20 return (createStore) => (reducer, preloadedState, enhancer) => {
21 var store = createStore(reducer, preloadedState, enhancer)
22 var dispatch = store.dispatch
23 var chain = []
24
25 var middlewareAPI = {
26 getState: store.getState,
27 dispatch: (action) => dispatch(action)
28 }
29 chain = middlewares.map(middleware => middleware(middlewareAPI))
30 dispatch = compose(...chain)(store.dispatch)
31
32 return {
33 ...store,
34 dispatch
35 }
36 }
37}