How to Cancel Previously Triggered API Requests in React Using Fetch API

How to Cancel Previously Triggered API Requests in React Using Fetch API

You can cancel previous API requests in React using the Fetch API with the AbortController interface. Here's how:

Steps to Cancel API Requests in React using Fetch API:

  1. Create an AbortController instance:

    • The AbortController provides an AbortSignal object that can be passed to the fetch method to allow aborting the request.
  2. Pass the AbortSignal to the Fetch request:

    • The AbortSignal is used in the fetch method to listen for an abort event.
  3. Abort the previous request:

    • Before making a new API request, you should abort any previous requests by calling the abort() method on the AbortController instance.
  4. Handle component unmount:

    • It's also important to cancel any ongoing requests if the component unmounts to prevent memory leaks.

Example Implementation:

Here’s an example of how you might implement this in a React component:

import React, { useEffect, useState, useRef } from "react";

const MyComponent = () => {
  const [data, setData] = useState(null);
  const [query, setQuery] = useState("initial query");
  const controllerRef = useRef(null);

  useEffect(() => {
    // Abort the previous request if there's one
    if (controllerRef.current) {
      controllerRef.current.abort();
    }

    // Create a new AbortController
    const controller = new AbortController();
    controllerRef.current = controller;

    const fetchData = async () => {
      try {
        const response = await fetch(`https://api.example.com/data?query=${query}`, {
          signal: controller.signal,
        });
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        const result = await response.json();
        setData(result);
      } catch (error) {
        if (error.name === "AbortError") {
          console.log("Fetch aborted");
        } else {
          console.error("Fetch error:", error);
        }
      }
    };

    fetchData();

    // Cleanup function to abort fetch on component unmount
    return () => {
      controller.abort();
    };
  }, [query]);

  return (
    <div>
      <input
        type="text"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />
      <div>{data && JSON.stringify(data)}</div>
    </div>
  );
};

export default MyComponent;

Explanation:

  1. AbortController and AbortSignal:

    • controllerRef is used to store the AbortController instance. By storing it in a ref, we ensure it persists between renders without causing re-renders.
  2. Effect Hook:

    • In the useEffect hook, we first abort any ongoing request by calling controllerRef.current.abort(). This prevents the previous request from completing if a new request is triggered.

    • Then, we create a new AbortController for the new request.

  3. Cleanup:

    • The cleanup function in the useEffect hook ensures that any ongoing request is canceled if the component unmounts.
  4. Handling Abort Error:

    • We check if the error thrown is an "AbortError" to distinguish between an aborted request and other errors.

This approach makes sure that only the latest request is handled. This is very useful for things like search inputs, where many API requests can happen quickly one after another.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!