score:3

Accepted answer

if you take a quick look at the source you will see that it's the applymiddleware function that injects the middleware api into each middleware.

export default function applymiddleware(...middlewares) {
  return createstore => (...args) => {
    const store = createstore(...args)
    let dispatch = () => {
      throw new error(
        `dispatching while constructing your middleware is not allowed. ` +
          `other middleware would not be applied to this dispatch.`
      )
    }
    let chain = []

    const middlewareapi = {
      getstate: store.getstate,
      dispatch: (...args) => dispatch(...args)
    }

    // here is the interesting part where we pass in the dispatch
    // and getstate functions
    chain = middlewares.map(middleware => middleware(middlewareapi))
    dispatch = compose(...chain)(store.dispatch)

    return {
      ...store,
      dispatch
    }
  }
}

this is directly from the redux source code linke here!. i could go into more details but i actually wrote about this here, so check it out as i go into details about this exact question. i hope this helps, let me know if you have other questions!

score:3

it's all about curry functions and closures. the middleware function you provide is internally mapped called via compose while the getstate and dispatch are passed as an argument object. the following code from redux code should be helpful: https://github.com/reactjs/redux/blob/master/src/applymiddleware.js#l30-l40

let chain = []

const middlewareapi = {
  getstate: store.getstate,
  dispatch: (...args) => dispatch(...args)
}
chain = middlewares.map(middleware => middleware(middlewareapi))
dispatch = compose(...chain)(store.dispatch)

return {
  ...store,
  dispatch
}

as you can see "chain" is the mapped array of function with the getstate and dispatch object as argument. hope this helps you to understand how the middleware works


Related Query

More Query from same tag