Cancel fetch request in Javascript.


What does cancel fetch request mean?
When you start an API call but cancel it before it completes, it's called canceling a fetch request.
What is the need to cancel a fetch request?
Resources associated with the request get freed up.
It prevents unnecessary data transfer and parsing of the response.
It prevents accidental overwriting of newer information when an old(stale) request finishes after a newer one.
How to cancel a fetch request?
Cancellation of a fetch request can be done through AbortController API. You need to create an instance of AbortController and pass its signal property as an option to the fetch function.
Cancel fetch request in JS.
// Create an instance of AbortController to control the fetch request
const controller = new AbortController();
// Extract the signal from the controller to pass to the fetch request
const signal = controller.signal;
// Initiate the fetch request with the AbortController's signal
fetch("https://fakestoreapi.com/products", { signal })
.then(res => res.json()) // Convert the response into JSON
.then(data => console.log(data)) // Log the fetched data to console
.catch((error) => {
// If the request was aborted, handle it here
if (error.name === "AbortError") {
console.log("Fetch request was cancelled.");
} else {
// Handle other types of errors
console.error("Fetch error:", error);
}
});
// Cancel the fetch request after 200 milliseconds
setTimeout(() => {
controller.abort(); // Aborts the fetch request
}, 200);
Cancel fetch request in React.
// Import necessary modules
import "./styles.css";
import { useEffect, useState } from "react";
// Main App component
export default function App() {
// State to store fetched data
const [data, setData] = useState([]);
// Function to fetch data from the given URL
async function fetchData(URL, signal) {
try {
// Fetch request with the provided URL and signal for cancellation
const response = await fetch(URL, { signal });
// Parse the JSON response and set it to state
const data = await response.json();
setData(data);
} catch (error) {
// Handle the error if the request was aborted
if (error.name === "AbortError") {
console.log("Fetch request was cancelled.");
} else {
// Handle other types of errors
console.error("Fetch error:", error);
}
}
}
// useEffect hook for fetching data on component mount
useEffect(() => {
// Step 1: Create an AbortController instance for canceling the fetch request
const controller = new AbortController();
// Step 2: Get the signal property from the controller
const signal = controller.signal;
// Step 3: Call the fetchData function with the URL and signal for cancellation
fetchData("https://fakestoreapi.com/products", signal);
// Cleanup function: Abort the request when the component is unmounted
return () => {
controller.abort();
};
}, []); // Empty dependency array ensures this effect runs once on component mount
// Render the fetched data as a list of product titles
return (
<div className="App">
{data?.map((product) => {
// Return a paragraph element for each product title
return <p key={product?.id}>{product?.title}</p>;
})}
</div>
);
}
Use cases:
A user is typing quickly into the search box.
For every keystroke, a new API call is made. To fix this, cancel the previous fetch request when a new one is triggered.You fetch data when the component mounts, but the user navigates away before the request finishes.
In this case, abort the request when the component unmounts.Timeout for slow requests.
You want to cancel the fetch if it takes too long. Normally, set a timeout and abort the fetch if it exceeds that time limit.
Thank You for Reading!
I truly appreciate you taking the time to read this blog. I hope the information was helpful and gave you new insights. If you have any questions or feedback, feel free to reach out. Keep learning and coding!
Happy Coding! ๐
Aman Verma
Aman Verma's Linkedin
Subscribe to my newsletter
Read articles from Aman Verma directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
