Multiple parallels api call

Viewed 30

I'm using redux-saga and redux libraries to handle my project in React.
I'll explain my issue: in one moment the frontend application will dispatch n multiple identical saga "CUSTOM_ACTION" action (expected behaviour). Now I'd like to have only one api calls even the actions are multiple. Take latest option doesn't work.
This my saga code:

function* testWorker() {
// call api only once
}

function* testWatcher() {
yield takeLatest("CUSTOM_ACTION", testWorker);
}

With this configuration I have n api calls, one for each action.
How can I solve my problem?
Thanks in advance to everyone who can help me

1 Answers

The answer kind of depends on what you mean by "in one moment".

If you mean that only one request should be running at a time, you can use the takeLeading effect instead of takeLatest. It will start the request for the first action dispatched an ignore all the others until the request saga is finished.

function* testWatcher() {
  yield takeLeading("CUSTOM_ACTION", testWorker);
}

If you mean some specific time, you can use the debounce effect. It will run only a single saga for a given time (once the time is over, with the last action dispatched).

function* testWatcher() {
  yield debounce(500, "CUSTOM_ACTION", testWorker);
}

You can run it with 0 for a very short amount of time.

There is also the throttle effect if you just want to limit the amount of requests created.

Related