Clue Mediator

How to cancel a Fetch request in React

๐Ÿ“…June 7, 2023
๐Ÿ—ReactJS

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:
const abortController = new AbortController();
  • Pass the signal property of the AbortController to the fetch request's options:
fetch(url, { signal: abortController.signal })
  .then(response => {
    // Process the response
  })
  .catch(error => {
    // Handle errors
  });
  • To cancel the fetch request, call the abort() method on the AbortController:
abortController.abort();

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

App.js

import React, { useState, useEffect } from 'react';

const App = () => {
  const [data, setData] = useState(null);
  const abortController = new AbortController();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('https://hub.dummyapis.com/delay?seconds=5', { signal: abortController.signal });
        const textData = await response.text();
        setData(textData);
      } catch (error) {
        if (error.name === 'AbortError') {
          // Request was cancelled
          setData('Request Aborted!')
          return;
        }
        // Handle other errors
      }
    };

    fetchData();

    return () => {
      abortController.abort(); // Cancel the request if component unmounts
    };
  }, []);

  const handleAbort = () => {
    abortController.abort(); // Cancel the request
  }

  return (
    <div>
      <h3>How to cancel a Fetch request in React - <a href="https://cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h3>

      <div>Click on Abort button to cancel the request.</div>
      <button onclick="{()" ==""> handleAbort()}>Abort</button>

      <div>Request Response:<br>{data}</div>
    </div>
  );
};

export default App;

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