Created
September 23, 2019 20:45
-
-
Save udfalkso/bad1ae379ddb7b30c7016d49a38e2f2a to your computer and use it in GitHub Desktop.
redux saga takeLatestPerActionAttr more specific takeLatest
This file contains 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
/* | |
* Custom variant on redux saga's takeLatest that allows us to resolve race condition for data updates | |
* based on something more specific than just the action type. | |
* This accepts an action type (e.g. FETCH_DATA) as well as a fn that that extracts a value from the action | |
* itself. (e.g. (a) => a.module.id) to get action attribute value. We can then effectively do a takeLatest for the action+value | |
* combination and ensure that only the latest action for each combo isn't cancelled. | |
* */ | |
export const takeLatestPerActionAttr = (actionType, attrFn, saga, ...args) => | |
fork(function*() { | |
const lastTasks = {} | |
while (true) { | |
const action = yield take(actionType) | |
const attrVal = attrFn(action) | |
const lastTask = lastTasks[attrVal] | |
if (lastTask) { | |
yield cancel(lastTask) // cancel is no-op if the task has already terminated | |
} | |
lastTasks[attrVal] = yield fork(saga, ...args.concat(action)) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment