Home > Blockchain >  Is there a way to prevent fetching when `refetch` method get called? react-query
Is there a way to prevent fetching when `refetch` method get called? react-query

Time:01-12

I have custom fetching hook which uses useQuery - from react-query. How can I prevent fetching/refetching based on the boolean prop I provide. At the moment I am using { enabled: allowedToFetch } but this doesn't prevent from fetching when I use refetch method from react-query.

CodePudding user response:

It is per design that refetch returned from useQuery performs an unconditional fetch and even bypasses enabled.

This is very well documented here: https://react-query.tanstack.com/guides/disabling-queries

This is necessary so that you can opt-out of smart refetching and go into "manual" mode by setting enabled: false and using refetch().

queryClient.refetchQueries and queryClient.invalidateQueries respects enabled, as do all the smart refetches.

The question is: Why do you have a disabled query where you call refetch on but do not want it to actually refetch? What's the use case?

if the condition is: enabled: allowedToFetch, I would either:

.) wrap the refetch call in the same condition:

if (allowedToFetch) {
  refetch()
}

.) or use local state to drive the query (the preferred solution):

const [allowedToFetch, setAllowedToFetch] = useState(false)

useQuery(key, fn, { enabled: allowedToFetch })

now all you need to do to get a refetch is to call:

setAllowedToFetch(true)

this will enable the query and react-query will do the rest.

  •  Tags:  
  • Related