Skip to content

Instantly share code, notes, and snippets.

@r3dm1ke
Last active February 15, 2020 17:45
Show Gist options
  • Select an option

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

Select an option

Save r3dm1ke/19245f1fd59e2852101c10c0c9307e4a to your computer and use it in GitHub Desktop.
Support for handling interceptors after dispatching actions
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