0

The React documentation for componentWillUnmount() implies that it is possible to cancel network requests:

Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, ...

But answers here say it is not possible.

Question being, is it possible or not to cancel a network requests in JS?

For example, if I started a setInterval to requests using the Fetch API in componentDidMount, and on some condition I want to stop requests, doing so in componentWillUnmount per the documentation. How can I cancel all network requests? I'm not talking about calling clearInterval, which will stop the timer. I want to make sure that any network requests that were started will be canceled in a given condition.

Ry-
  • 218,210
  • 55
  • 464
  • 476
Green
  • 28,742
  • 61
  • 158
  • 247
  • Read the second answer to the question you linked. "Network requests" doesn’t have to mean Fetch, either; XHR has [`.abort()`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/abort). – Ry- Feb 22 '18 at 18:31
  • 1
    https://stackoverflow.com/questions/31061838/how-do-i-cancel-an-http-fetch-request – epascarello Feb 22 '18 at 18:32
  • @epascarello that's the "answers here" link – Ry- Feb 22 '18 at 18:32
  • [window.stop()](https://developer.mozilla.org/en-US/docs/Web/API/Window/stop) – ryan Feb 22 '18 at 18:32
  • Well that link says it is possible in browsers that support. Look at the second answer. – epascarello Feb 22 '18 at 18:33

1 Answers1

1

It seems that this is just an experimental API. Therefore, yes it is possible, but no not in all browsers.

https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort

EDIT

For plain AJAX request it is definitely possible: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/abort

Arwed Mett
  • 2,614
  • 1
  • 22
  • 35