How to cancel Javascript API request with AbortController
The fetch API is a JavaScript API for making HTTP requests. It is a replacement for XMLHttpRequest, which is deprecated in most browsers. It is a promise-based API, meaning that it returns a Promise object that is resolved or rejected when the request is complete.
Let’s take a look at the fetch() function.
fetch(url)
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error));
This is great but sometimes we want to cancel the already initiated request.
Let’s take a look at the following example.
Suppose we have search input we want to show the suggestions as to the user types. when the user types a character, we call the fetch() function and pass the value of the search input field as the URL parameter.
fetch(`${url}?q=${searchInput.value}`)
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error));
Problem:
The fetch() function is called every time the user types a character, This is an inefficient approach as it is called multiple times and we are only interested in the last response.