Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

270
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda