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

433
Visualizações
React query - cancel pending or previous requests

I am trying to cancel any previous / pending requests, if they are taking too long and the user navigates to another component, currently the query takes in a state value, and when it changes the component re-renders which is fine and the desired behaviour. However looking in the network tab the requests are still pending. Is there a way in react query to cancel any previous requests. I have attempted the query cancel based on the docs but its not correct as it's not cancelling.

  const [value, setValue] = React.useState<boolean>(false);

  const getData = async (value: number): Promise<any> => {
    const CancelToken = axios.CancelToken
    const source = CancelToken.source()
    const response = await axios.get(`https://xxxxxx?value=${value}`, {
        cancelToken: source.token,
    }).then(res => res.data);
    if (CancelToken) {
        response.cancel = () => {
            source.cancel('Query was cancelled by React Query')
        }
    }
    return response;
}

const { data: result, status, error, isFetching }: any = useQuery(['getData', value], () => getData(value),
    {
        refetchOnWindowFocus: false,
    }
);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You cannot attach .cancel to a promise in an async functions because async functions will always return a new Promise without the cancel function you attached. If you want to attach a cancel functions, it's best to use promise chaining instead of async functions.

Even better, react-query supports cancellation now by providing an AbortSignal out of the box, which you only need to attach to your request.

with axios 0.22+ and react-query v3.30+, you can do:

 const query = useQuery('key', ({ signal }) =>
   axios.get('/xxxx', {
     signal,
   })
 )

with that, react-query will cancel the network request of your query if the query becomes unused or if you call queryClient.cancelQueries('key'), e.g. when the user clicks a button.

about 4 years ago · Juan Pablo Isaza Relatório

0

You need to throw out an error based on the response in your getData(). React-Query will catch that error and trigger the onError event.

about 4 years ago · Juan Pablo Isaza Relatório
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