T
TanStack3y ago
plain-purple

Creating a query that polls an endpoint but ends when server returns specific value

I'm currently using RTK Query in a project at work and it allows you to do things like this:
const { currentData, isError } = api.endpoints.pollingEndpoint.useQueryState(args);
usePollingEndpointQuery(args, { pollingInterval: 3000, skip: !args || currentData?.complete })
const { currentData, isError } = api.endpoints.pollingEndpoint.useQueryState(args);
usePollingEndpointQuery(args, { pollingInterval: 3000, skip: !args || currentData?.complete })
...but in practice there are problems under the hood that prevent this from being a great solution. What's the cleanest way to do this in React Query? Is it "supported"? Does anyone have any experience using React Query for a use case like this?
3 Replies
genetic-orange
genetic-orange3y ago
you're looking at refetchInterval option for useQuery https://tanstack.com/query/v4/docs/react/reference/useQuery#:~:text=refetchInterval%3A%20number%20%7C%20false%20%7C%20((data%3A%20TData%20%7C%20undefined%2C%20query%3A%20Query)%20%3D%3E%20number%20%7C%20false) e.g.
useQuery(queryKey, queryFn, {
refetchInterval: (data) => !data.complete ? 3000 : false
}
useQuery(queryKey, queryFn, {
refetchInterval: (data) => !data.complete ? 3000 : false
}
plain-purple
plain-purpleOP3y ago
Let's say I need the query to stop when it returns a specific value.
generous-apricot
generous-apricot3y ago
You can pass a function to refetchInterval for that purpose

Did you find this page helpful?