AbortSignal and AbortController

MDN AbortSignal MDN AbortController

The AbortController interface represents a controller object that allows you to abort one or more Web requests as needed. The **AbortSignal ** interface represents a signal object that allows you to communicate with DOM requests (such as Fetch) via the AbortController object and abort them as needed.

Here is the official sample code, which uses FETCH to download the video. AbortController is used to create a controller instance, Controller. Controller.signal is the second argument to the fetch request. After the fetch request is made, controller.abort() is used to abort the request.

var controller = new AbortController();
var signal = controller.signal;

var downloadBtn = document.querySelector('.download');
var abortBtn = document.querySelector('.abort');

downloadBtn.addEventListener('click', fetchVideo);

abortBtn.addEventListener('click'.function() {
  controller.abort();
  console.log('Download aborted');
});

function fetchVideo() {... fetch(url, {signal}).then(function(response) {... }).catch(function(e) {
    reports.textContent = 'Download error: '+ e.message; })}Copy the code

Note: When abort() is called, fetch() calls Reject, returning an AbortError.

How to use React Hook?

const App = () = > {
 const abortController = React.useRef()

 React.useEffect(() = > {
  // Abort if there is a pending fetch
  if (abortController.current) {
    abortController.abort()
  }
  // Regenerate a new AbortController example
  abortController.current = new AbortController()
  const { signal } = abortController.current

  fetch(url, { signal }).then(res= > {
    // ...
  })
 }, [
  abortController,
  ...
 ])
}
Copy the code

This article has partially translated this article, you can also go to the original article.