Skip to content

Instantly share code, notes, and snippets.

@r3dm1ke
Created January 26, 2020 15:36
Show Gist options
  • Select an option

  • Save r3dm1ke/fb81f37446cc39280191a8e5b1121450 to your computer and use it in GitHub Desktop.

Select an option

Save r3dm1ke/fb81f37446cc39280191a8e5b1121450 to your computer and use it in GitHub Desktop.
applyMiddleware from Redux (simplified)
import compose from './compose'
import { Middleware, MiddlewareAPI } from './types/middleware'
import { AnyAction } from './types/actions'
import { StoreEnhancer, StoreCreator, Dispatch } from './types/store'
import { Reducer } from './types/reducers'
export default function applyMiddleware(
...middlewares: Middleware[]
): StoreEnhancer<any> {
return (createStore: StoreCreator) => <S, A extends AnyAction>(
reducer: Reducer<S, A>,
...args: any[]
) => {
const store = createStore(reducer, ...args)
let dispatch: Dispatch = () => {
throw new Error(
'Dispatching while constructing your middleware is not allowed. ' +
'Other middleware would not be applied to this dispatch.'
)
}
const middlewareAPI: MiddlewareAPI = {
getState: store.getState,
dispatch: (action, ...args) => dispatch(action, ...args)
}
const chain = middlewares.map(middleware => middleware(middlewareAPI))
dispatch = compose<typeof dispatch>(...chain)(store.dispatch)
return {
...store,
dispatch
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment