The Fetch API supports cancelling requests using AbortController
interface. We can therefore cancel in-flight requests in our applications without the need for including external fetching libraries like axios.
const controller = new AbortController();
const { signal } = controller;
fetch("http://localhost:8000", { signal }).then(response => {
// do something
}).catch(e => {
// called on cancel
console.error(`Error: ${e.message}`);
});
// Abort the request
controller.abort();
Above we can see how we can use an AbortController
to cancel an in-flight fetch request.
But this basic example is not indicative of how you would use this API in your applications. Let’s instead look at a real world example.
#react #typescript #programming #javascript #nextjs