'Retry react-query based on result

I want the query to retry until the expected result is met. How do I pass a condition into the function to decide if the query succeeded or not?

export async function waitUntilQuerySucceeds(
  id: Id,
  queryKey: QueryKey,
  queryClient: QueryClient,
  retryInterval = 500,
  amountOfAttempts = 12,
) {
  let attempts = 0
  let results: [] | undefined = queryClient.getQueryData([queryKey, id])
  while (attempts < amountOfAttempts) {
    const result = results?.find(p => p.Id === id)
    if (result) return true

    attempts += 1
    await queryClient.refetchQueries([queryKey, id])
    await wait(retryInterval)
    results = queryClient.getQueryData([queryKey, id])
  }
  return false
}

function wait(timeout: number) {
  return new Promise(resolve => {
    setTimeout(resolve, timeout)
  })
}


Solution 1:[1]

export async function waitUntilQuerySucceeds(
  id: Id,
  queryKey: QueryKey,
  queryClient: QueryClient,
  retryInterval = 500,
  amountOfAttempts = 12,
) {
  let isDataFetched = false
  let attempts = 0
  let results: [] | undefined = queryClient.getQueryData([queryKey, id])
  while (attempts < amountOfAttempts && !isDataFetched) {
    const result = results?.find(p => p.Id === id)
    if (result) isDataFetched = true;

    attempts += 1
    await queryClient.refetchQueries([queryKey, id])
    await wait(retryInterval)
    results = queryClient.getQueryData([queryKey, id])
  }
  return false
}

function wait(timeout: number) {
  return new Promise(resolve => {
    setTimeout(resolve, timeout)
  })
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 iliyass