Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

267
Views
Calling AbortController.abort() on resolved fetch

I have a React app that can makes a series of fetch requests, depending on user interactions. I want to abort old fetch requests any time the app receives a new one.

To accomplish this, I've created a custom hook, useData. Its main fucntion is running a useEffect hook whenever the url changes. The easiest way to abort old requests seems to me to be using the cleanup mechanism provided by useEffect. But this will call abort on all requests, not just incomplete ones.

Are there any hidden problems this might cause? It seems that it shouldn't do much to a resolved fetch, but I can't find any documentation to support that.

This is my code:

/** Returns data for a given url. */
export const useData = function (dataUrl) {
  const [loadedData, setLoadedData] = useState(Object.assign({}));

  // runs if/when the url changes
  useEffect(() => {
    // new controller for each new url
    const controller = new AbortController();
    
    async function getData(dataUrl) {
      if (!dataUrl) return;

      // load data & set state
      try {
        const data = await fetch(dataUrl, {
          signal: controller.signal,
        });
        setLoadedData(data);
      } catch (e) {
        console.error(`useData failed for url ${dataUrl}\n${e}.`);
      }
    }

    getData(dataUrl);

    // clean up the last request before running 
    // useEffect for on the next url
    return () => {
      controller.abort();
    };

  }, [dataUrl]);

  // return data in the hook's state, set by useEffect
  return loadedData;
};
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!