Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeatedly send request to a same API using react-query? [duplicate]

I want to use react-query to send the request and check a field of the response right after. Once I found the field I need in the response, stop doing more action. Otherwise, keep executing the request again until I find the field.

const queryResult = useQuery({ queryKey: ['test','testDataId'], queryFn: ({queryKey}) => fetchTestData(queryKey[1]),
});
like image 556
Ray Avatar asked Mar 25 '26 18:03

Ray


2 Answers

There is another way also you can try by adding retry params and also manage the delay through retryDelay:

ex.

const result = useQuery({
  queryKey,
  queryFn: ({queryKey}) => fetchTestData(queryKey[1]),
  retry: 10, // Will retry failed requests 10 times before displaying an error
})

You can also add a function in it for manage based on status

const result = useQuery({
  queryKey,
  queryFn: ({queryKey}) => fetchTestData(queryKey[1]),
  retry: (count, {message: status}) => (status !== '404' && status !== '401')
  // You can add logic based on your requirement and status code.
})

references link:

https://tanstack.com/query/v4/docs/guides/query-retries

React Query keeps retrying despite 'enabled' set to false

like image 149
Jatin Bhuva Avatar answered Mar 27 '26 08:03

Jatin Bhuva


You can achieve this using invalidateQueries, which will mark the current data as stale and trigger a re-fetch in the background (as long as you don't pass it refetchType: 'none').

In your onSuccess, add this (wrapped in the check for the field you are looking for):

queryClient.invalidateQueries({ queryKey: [queryKey] });
like image 27
David Mason Avatar answered Mar 27 '26 07:03

David Mason