0

The test condition is that we are calling 3-4 API's at a time one after another and the API's take time to load a bit. During that time if we press the back button or any other UI component it responds after all the API has been called. So I want to cancel the API on button click.

export function* getData(api, action) {
  const { location } = action;
  // make the call to the api
  const response = yield call(api.daily, location);
  if (response.status === 200) {
    // do data conversion here if needed
    yield put(LocationActions.Success(response.data));
  } else {
    const error = errorType(response);
    yield put(Actions.Failure(error));
  }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rishav Kumar
  • 4,979
  • 1
  • 17
  • 32
  • Can you put up some code ? Can't help you without informations – Fakebounce May 22 '19 at 09:25
  • Code? I can but that won't be required becuase existing code has least to do. Still, I'll upload a demo code : ) – Rishav Kumar May 22 '19 at 10:24
  • Sorry i didn't see redux-saga tag. Did you read the doc ? https://redux-saga.js.org/docs/advanced/TaskCancellation.html You can yield take an action like a back button press and cancel your current call. If you want to cancel the API call itself, you can cancel your API call through a yield put instead of cancel. If your API is REST you can check this : https://stackoverflow.com/questions/31833178/how-to-cancel-a-rest-api-request – Fakebounce May 22 '19 at 12:01
  • @hardworker Went through it but the code was not that clear to me so I thought to add a follow up in stack overflow if someone can help. : ) – Rishav Kumar May 22 '19 at 12:02
  • Use [`race`](https://redux-saga.js.org/docs/advanced/RacingEffects.html) to wait for cancel or API response. – Joseph D. May 23 '19 at 01:38

1 Answers1

0

The lodash library should do the trick:

// create debounce
debouncedThing = _.debounce(thing, 1000);

// execute debounced api call
this.debouncedThing();

// onpress button
debouncedThing.cancel()

More details on this answer

See the lodash library for more infos about installation and usage.

Poptocrack
  • 2,879
  • 1
  • 12
  • 28
  • I think this won't work in my case. debouncedThing = _.debounce(thing, 1000); This code means that it will make the API wait for 1 sec and then execute. My issue is that the API takes 10 seconds to load. What if the API call has been executed and after 5-second user wants to cancel the call. This won't be appropriate! – Rishav Kumar May 22 '19 at 10:32