Skip to content

Instantly share code, notes, and snippets.

@StevenJL
Created July 21, 2019 08:24
Show Gist options
  • Select an option

  • Save StevenJL/6c064a21a487a4eb78e8ea71e67d5da5 to your computer and use it in GitHub Desktop.

Select an option

Save StevenJL/6c064a21a487a4eb78e8ea71e67d5da5 to your computer and use it in GitHub Desktop.
Apply 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.'
)
}
const middlewareAPI = {
getState: store.getState,
dispatch: (...args) => dispatch(...args)
}
const chain = middlewares.map(middleware => middleware(middlewareAPI))
dispatch = compose(...chain)(store.dispatch)
return {
...store,
dispatch
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment