sp-dev-docs icon indicating copy to clipboard operation
sp-dev-docs copied to clipboard

How to cancel API requests?

Open jayeshvg opened this issue 8 years ago • 4 comments

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

jayeshvg avatar Nov 28 '18 15:11 jayeshvg

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.

patmill avatar Nov 28 '18 18:11 patmill

As @patmill said, use debounce js feature to cancel previous request after certain milliseconds so no api request is made until typing is done.

jonathanhotono avatar Nov 29 '18 05:11 jonathanhotono

Closing as answered with previous comments.

VesaJuvonen avatar Jan 10 '19 18:01 VesaJuvonen

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

msft-github-bot avatar Jan 26 '20 00:01 msft-github-bot