Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

272
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda