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

180
Visualizações
How can I check the react-query queries before execute?

For example, I've this query to fetch a list:

const list = useQuery('list', fetcher);

But I need something like a prechecking function before react-query execute that, I mean something like this:

const appQueryClient = new QueryClient({
  defaultOptions: {
    queries: {
      checkSomethingBeforeExecute: () => {
        if (itShouldExecute) {
          return true; // start fetching
        } else {
          return false; // don't fetch and abort query
        }
      }
    },
  },
});

In fact, that checkSomethingBeforeExecute is my idea... but I'm looking for any option or trick to implement something like that. If you remember, there is a select option to transform data after fetching, but I need something to determine query exec before anything start with fetcher function.

##new update##

I updated my question for this example:

import React, { useState } from "react";
import ReactDOM from "react-dom";
import { QueryClient, QueryClientProvider, useQuery } from 'react-query';

const client = new QueryClient({
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false,
      retry: false
    }
  }
});

const fetcher = () => fetch('https://randomuser.me/api/?results=5').then(res => res.json());

function App() {
  const [id, setId] = useState(null);
  const { data } = useQuery(['list', id], fetcher, { enabled: !!id });

  const change = (e) => {
    setId(e.target.value);
  }

  return (
    <div>
      <select onChange={change}>
        {
          Array(30).fill().map((i, ii) => <option value={ii} key={ii}>item - {ii}</option>)
        }
      </select>
    </div>
  )
}

const rootElement = document.getElementById('root');
ReactDOM.render(<QueryClientProvider client={client}><App /></QueryClientProvider>, rootElement);

There is a select input to handle changing state for each id and react-query doesn't retrieve cache and fetches again for even same IDs...

Thanks

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

if your query is not ready to be executed, the enabled option is what you are looking for:

https://react-query.tanstack.com/guides/dependent-queries

if you want to "not fetch" and "abort" the query (not sure what aborting means here), you can return a rejected Promise from your queryFn:

useQuery(key, () => {
  if (itShouldExecute) {
    return axios.get(...)
  }
  return Promise.reject(new Error("something error"))
})

be aware that this will put the query in an error state and potentially trigger retries. The enabled option will not run the queryFn at all and will put your query into idle state. I think these are the two available options.

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