Created
January 26, 2020 15:36
-
-
Save r3dm1ke/fb81f37446cc39280191a8e5b1121450 to your computer and use it in GitHub Desktop.
applyMiddleware from Redux (simplified)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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