Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save abner/c4e6dd5633396b4cca0cb52f2de840af to your computer and use it in GitHub Desktop.
Save abner/c4e6dd5633396b4cca0cb52f2de840af to your computer and use it in GitHub Desktop.
Redux Async middleware - Add a convient way to dispatch new action from an action
const asyncDispatcMiddleware = store => next => action => {
let syncActivityFinished = false;
let actionQueue = [];
function flushQueue() {
actionQueue.forEach(a => store.dispatch(a));
actionQueue = [];
}
function asyncDispatch(asyncAction) {
actionQueue = actionQueue.concat([asyncAction]);
if (syncActivityFinished) {
flushQueue();
}
}
const actionWithAsyncDispatch = Object.assign({}, action, {asyncDispatch});
next(actionWithAsyncDispatch);
syncActivityFinished = true;
flushQueue();
};
export default asyncDispatcMiddleware;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment