3

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]),
});
Kirill Novikov
  • 2,576
  • 4
  • 20
  • 33
Ray
  • 85
  • 7

3 Answers3

2

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

Jatin Bhuva
  • 1,301
  • 1
  • 4
  • 22
  • A good and simple idea. But it seems I have to throw an error manually to trigger the retry function. It might not suitable for my real coding situation, but helpful. – Ray Dec 16 '22 at 08:54
1

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] });
David Mason
  • 2,917
  • 4
  • 30
  • 45
0

I found a clue that might be helpful: react-query QueryClient

const queryClient = useQueryClient();
const queryKey = ['test','testDataId'];

const queryResult = useQuery({ 
  queryKey,
  queryFn: ({queryKey}) => fetchTestData(queryKey[1]),
  // Adjust the `responseData` structure,can be omitted.
  select: (result) => result.data,
  onSuccess(responseData){
    if (responseData.refreshing === true) {
      // Crucial action, mark the query with queryKey as staled
      queryClient.invalidateQueries({queryKey})
    }
  }
});

Ray
  • 85
  • 7