Last active
February 15, 2020 17:45
-
-
Save r3dm1ke/19245f1fd59e2852101c10c0c9307e4a to your computer and use it in GitHub Desktop.
Support for handling interceptors after dispatching actions
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
| const createInterceptorMiddleware = (interceptors) => (store) => (next) => (action) => { | |
| Promise.all( | |
| interceptors | |
| .filter(interceptor => interceptor.type === action.type) | |
| .map(interceptor => { | |
| const result = interceptor.handler(action, store.dispatch, store.getState); | |
| return result instanceof Promise ? result : Promise.resolve(result); | |
| }) | |
| ) | |
| .then((afterDispatchHandlers) => { | |
| next(action); | |
| afterDispatchHandlers.forEach( | |
| handler => | |
| typeof handler === 'function' && | |
| handler(action, store.dispatch, store.getState) | |
| ); | |
| }) | |
| .catch(e => console.error(e)); | |
| } | |
| const interceptors = [ | |
| {type: 'INCREMENT', handler: () => doSomeApiStuff()}, | |
| { | |
| type: 'DECREMENT', | |
| handler: () => { | |
| doOtherApiStuff(); | |
| return () => doCleanup(); | |
| } | |
| } | |
| ]; | |
| const middleware = createInterceptorMiddleware(interceptors); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment