How to cancel a Fetch request in React

In React, canceling a fetch request is a common requirement when dealing with asynchronous data fetching. One approach to achieve this is by utilizing the AbortController API, which provides a way to abort ongoing fetch requests. By creating an instance of AbortController and passing its signal property to the fetch request, you can easily cancel the request when needed. This can be particularly useful in scenarios where the user wants to interrupt or stop a long-running request or when navigating away from a component that initiated the request.

To implement this in a React component, you would typically create an AbortController instance and store it in a variable. Then, when making the fetch request, you pass the signal property from the AbortController to the fetch options. If the request needs to be canceled, you simply call the abort() method on the AbortController. By following these steps, you can gracefully handle the cancellation of fetch requests in React, providing a smoother and more responsive user experience when interacting with asynchronous data fetching in your applications.

Demo Application

Output - How to cancel a Fetch request in React - Clue Mediator
Output – How to cancel a Fetch request in React – Clue Mediator

How to cancel a Fetch request in React

  1. Project structure
  2. Package dependencies
  3. Implementation
  4. Output

1. Project structure

  • react-fetch-cancel-example
    • node_modules
    • public
      • index.html
    • src
      • App.js
      • index.css
      • index.js
    • package-lock.json
    • package.json
    • README.md

2. Package dependencies

You will find the version of the following packages in React application.

react
^18.2.0

3. Implementation

The AbortController provides a way to abort an ongoing fetch request by canceling it. Here’s how you can cancel a fetch request in React:

  • Create an AbortController instance and store it in a variable:
  • Pass the signal property of the AbortController to the fetch request’s options:
  • To cancel the fetch request, call the abort() method on the AbortController:

Here’s an example of how you can implement the cancellation of a fetch request in a React component:

App.js

Overall, this code block performs the fetch request, retrieves the response data, updates the state with the fetched data, and handles any potential errors, including the cancellation of the request using the AbortError check.

4. Output

Run your application and check the output in the browser.
Live Demo

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

GitHub Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *