From 24c6842f421eebf84dc5036574565bc6190bddd1 Mon Sep 17 00:00:00 2001 From: Pete Miller Date: Fri, 17 Jul 2020 00:46:02 -0700 Subject: [PATCH] Framework for async redux actions --- components/common/AsyncActionHandler.ts | 35 +++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 components/common/AsyncActionHandler.ts diff --git a/components/common/AsyncActionHandler.ts b/components/common/AsyncActionHandler.ts new file mode 100644 index 00000000000..54d716dc106 --- /dev/null +++ b/components/common/AsyncActionHandler.ts @@ -0,0 +1,35 @@ +import { MiddlewareAPI, Dispatch, Middleware, AnyAction } from 'redux'; + +type Handlers = Map + +/** + * Quick n easy redux middleware generator for async actions. + * Usage example: + * ``` + * const asyncActions = new AsyncHandler() + * asyncActions.on('action-type', ({ getState, dispatch }, payload) => { + * // do something with payload, getState, and dispatch + * // like call an async API, etc + * } + * Redux.createStore( + * myReducer, + * applyMiddleware(asyncActions.middleware) + * ) + * ``` + */ +export default class AsyncHandler { + handlersByType: Handlers = new Map() + + on(actionType: string, doStuff: (store: MiddlewareAPI, payload: T) => void) { + this.handlersByType.set(actionType, doStuff) + } + + middleware: Middleware = (store: MiddlewareAPI) => (next: Dispatch) => (action: AnyAction) => { + const result = next(action) + const doStuff = this.handlersByType.get(action.type) + if (doStuff) { + doStuff(store, next, action) + } + return result + } +} \ No newline at end of file