Created
June 13, 2018 09:46
-
-
Save GuillaumeNachury/695d2f4a7b03f0b0227fab23a431f3f8 to your computer and use it in GitHub Desktop.
Redux Async middleware - Add a convient way to dispatch new action from an action
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 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
Hello! Do you know how to setup this middleware on nextjs redux?