Search code examples
reduxredux-middleware

The implementation of Redux's applyMiddleware


My question is why middlewareAPI can't use :

const middlewareAPI = {
  getState: store.getState,
  dispatch: dispatch
}

to replace the definition in the source code as below:

export default function applyMiddleware(...middlewares) {
  return (createStore) => (reducer, preloadedState, enhancer) => {
    const store = createStore(reducer, preloadedState, enhancer)
    let dispatch = store.dispatch
    let chain = []

    const middlewareAPI = {
      getState: store.getState,
      dispatch: (...args) => dispatch(...args)   // why not just use `dispatch: dispatch`
    }
    chain = middlewares.map(middleware => middleware(middlewareAPI))
    dispatch = compose(...chain)(store.dispatch)

    return {
      ...store,
      dispatch
    }
  }
}

Anyone can tell me the difference ? Thanks.


Solution

  • It's a somewhat complicated combination of JS variable scoping/hosting, and needing to ensure that the passed-in dispatch method actually points back to the start of the middleware chain.

    Please see the newly-added (and not yet published) Redux FAQ entry on why applyMiddleware uses a closure for more details.