Skip to content

Instantly share code, notes, and snippets.

@diegocasmo
Created March 13, 2017 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diegocasmo/06186f61766987be30d242f0b7291307 to your computer and use it in GitHub Desktop.
Save diegocasmo/06186f61766987be30d242f0b7291307 to your computer and use it in GitHub Desktop.
Utility method that allows to create a Redux middleware and execute custom code before or after an action is dispatched.
import * as Immutable from 'immutable';
// Helper method for creating a middleware that handles the given set of actions
export function createMiddleware(handlers) {
return storeAPI => next => action => {
const actionHandler = Immutable.List(handlers).find(h => h.action.type === action.type);
// Execute custom middleware handler before the action is dispatched
if (actionHandler && actionHandler.beforeHandler) {
actionHandler.beforeHandler(storeAPI, action);
}
// Dispatch the action
const result = next(action);
// Execute custom middleware handler after the action is dispatched
if (actionHandler && actionHandler.afterHandler) {
actionHandler.afterHandler(storeAPI, action);
}
return result;
}
}
@diegocasmo
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment