How do I make takeLatest consider url, params, and method?

坚强是说给别人听的谎言 提交于 2019-12-11 07:50:59

问题


I'm using Saga's takeLatest to abort all requests except the latest. This works fine, but now I want to only abort requests which don't have identical url, params, and method.

I know Saga uses the type attribute to compare actions (just like vanilla Redux does), but I've also added url, params, and method to my actions because I was hoping there there was some way to do something like

yield takeLatestIf((action, latestAction) => {
    const sameType = action.type === latestAction.type;
    const sameUrl = action.url === latestAction.type;
    const sameParams = areEqual(action.params, lastAction.params);
    const sameMethod = action.method === lastAction.method;

    return sameType && sameUrl && sameParams && sameMethod;
});

which should only abort requests if all 4 of those attribute comparisons are false.

How can I accomplish this?


回答1:


If I get it right from your question, you want this:

  1. Like standard takeLatest().
  2. But when a duplicate request is made, ignore it and wait for the one already executing (a reasonable use case).

So I took takeLatest() implementation provided in the docs and adapted it to your scenario:

const takeLatestDeduped = (patternOrChannel, compareActions, saga, ...args) => fork(function*() {
  let lastTask
  let lastAction
  while (true) {
    const action = yield take(patternOrChannel)
    // New logic: ignore duplicate request
    if (lastTask && lastTask.isRunning() && !compareActions(lastAction, action)) {
      continue
    }
    if (lastTask) {
      yield cancel(lastTask)
    }
    lastTask = yield fork(saga, ...args.concat(action))
    // New logic: save last action
    lastAction = action
  }
})

We have three cases:

  1. No running task: start the new one - standard behavior
  2. Running task, got non-duplicate: cancel old one, start new one - standard behavior
  3. Running task, got duplicate: ignore - new custom hehavior

So I added case #3 logic:

  1. Ignoring duplicate request (nothing should be done in this case, so I continue to handling next action).
  2. Saving last action for future duplicate check.


来源:https://stackoverflow.com/questions/53731665/how-do-i-make-takelatest-consider-url-params-and-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!