How to cancel API requests?
Category
- [x] Question
- [ ] Typo
- [ ] Bug
- [ ] Additional article idea
Expected or Desired Behavior
How to cancel existing request/response when another call is made?
Observed Behavior
Steps to Reproduce
Let us say we have a text box to search certain sites. When I press another character or change some filter, I do not want old response to replace the results.
Submission Guidelines
There isn't anything specific in SPFx to handle this, but here are some thoughts -
1st, wait a bit after each keystroke before you send the request. Ie, wait for 250 or 500ms after the last keypress before sending a request. You don't want to flood the server with requests that you don't care about (and it will slow down your code). Even if you could cancel the request, if the server has got it already, it's going to execute.
2nd, you'll probably want to associate a request ID with your promise, and have a member variable that lists what the latest request ID was. When a promise completes, if the requestID isn't the latest one, then throw it away.
As @patmill said, use debounce js feature to cancel previous request after certain milliseconds so no api request is made until typing is done.
Closing as answered with previous comments.
Issues that have been closed & had no follow-up activity for at least 7 days are automatically locked. Please refer to our wiki for more details, including how to remediate this action if you feel this was done prematurely or in error: Issue List: Our approach to locked issues