Cancelling Fetch Requests in React Applications
By: Malcolm Laing
Tags: Programming, React, Typescript, JavaScript, Nextjs

Cancelling Fetch Requests in React Applications

Using useEffect, useRef and TypeScript

Photo by Jeremy Perkins on Unsplash

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.

Example of the `AbortController` API

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.

Cancelling Fetch Requests in React Applications

We will create a React application that allows users to type in a search term. Then our application will call an API, and return a list of matching users. We will call the API on every change of our input (we won’t debounce).

If there is an in flight request while the search term changes, we would like to cancel that request.

So let’s get started with a fresh NextJS application

npx create-next-app --example with-typescript cancel-fetch

Our API

Next, let’s open up the api that our example application starts with. Open the file api/users/index.ts . We will make a few modifications to the file.

In order to simulate real network requests, we will add two second timeout before our API call is returned. This makes it easier to test that our cancellations are working. We use the query param of req to filter out users who’s names don’t include this string.

Below you can see the modifications we made to the api/users/index.ts file.

Our Application

Now that we have our API work out of the way, let’s get started with our React application.

Our application will require two state variables. One to keep track of the search term, and another to keep track of the array of users we receive from the server. We can define our state variables as follows.

const [searchTerm, setSearchTerm] = useState("");

const [users, setUsers] = useState<User[]>([]);

Now that we have our state, we can define a useEffect hook where we call our API.

Now everytime a user types into our search input, we call our API and update our users state variable with the result. Notice how we haven’t yet added our cancellation feature.

To cancel in flight requests, we will need some mutable state to hold our AbortController instance. For this, we can use a ref .

const controllerRef = useRef<AbortController | null>();

We can then set and use our controllerRef variable inside our useEffect hook.

We can modify our function as follows. Notice how the first thing we do is abort any flight requests, then we define a new AbortController, assign it to our mutable state variable, and make our new request using that controller’s signal.

We add the catch block because fetch throws an error when requests are cancelled.

Now when we type into our search box, we can see the cancelled requests in our network tab.

Cancelled requests

Now we have created a React application that cancels any in flight requests using useEffect , useState and useRef . To see the full application code, check out the gist below.