Skip to content

How to use AbortController in React

In this post, I will show you how to use AbortController in React.

AbortController is a built-in JavaScript interface used to control and cancel asynchronous operations, especially those that return Promise objects, such as fetch() requests.

It provides a way to abort a request, preventing the operation from completing if, for example, the component is unmounted in a React application or if the user navigates away before the fetch completes.

Example Using AbortController with fetch in React

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

function FetchDataComponent() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // Create an instance of AbortController
    const controller = new AbortController();
    const signal = controller.signal;

    const fetchData = async () => {
      try {
        const response = await fetch('https://example.com/posts', 
            { signal }
        );
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        const result = await response.json();
        setData(result);
        setLoading(false);
      } catch (err) {
        if (err.name === 'AbortError') {
          console.log('Fetch request aborted');
        } else {
          setError(err.message);
          setLoading(false);
        }
      }
    };

    fetchData();

    // Cleanup function to abort the fetch if the component unmounts
    return () => {
      controller.abort();
    };
  }, []); 

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <div>
      <h1>Fetched Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export default FetchDataComponent;

In the above code snippet, we are using the AbortController interface to create a new controller object and then pass its signal property to the fetch method to abort the request when needed. We also update the loading state based on the request status and display the fetched data if available.