T
TanStack3y ago
eager-peach

Keep request running

"Is there a way to keep a request running while the server is still processing it? For instance, suppose I have an endpoint to check if the server is still processing a request. It will return a 204 status code if it is still processing it. Is there a way to repeatedly hit the endpoint until I receive a 200 status code indicating that the processing has finished?"
let res = checkStatus.mutate()

while (res.status === 204) {
await sleep(2000)
res = checkStatus,mutate()
}
let res = checkStatus.mutate()

while (res.status === 204) {
await sleep(2000)
res = checkStatus,mutate()
}
8 Replies
eager-peach
eager-peachOP3y ago
The code above works, I just feel like there is a better way to do it...
rising-crimson
rising-crimson3y ago
refetchInterval can accept a function so that you can poll until a certain criterion is met
eager-peach
eager-peachOP3y ago
But how can I implement this after the mutation that triggers the server-side processing? To illustrate, in the aforementioned code, I was executing it within the onSuccess function of the mutation that triggers the server-side process. With refetchInterval, I need to use useQuery and limit its execution to after the mutation, just to check it's status
extended-salmon
extended-salmon3y ago
Do you have control of the backend? We do something similar to this but the mutation provides a jobId, and then you can query the state of the job from a different endpoint. That way it feels closer to what these endpoints should do. E.g. only calling mutation once to trigger the work, and a separate query to see how it's getting on (with refetchInteval as TkDodo said)
eager-peach
eager-peachOP3y ago
Yes, I can do that, but can I use refetchInterval on a disabled query? I don't wan't it running automatically; I only want to utilize this query to display a loading status to the user and notify them when it's complete.
extended-salmon
extended-salmon3y ago
Yup, we only enable it when the jobId exists (so default is disabled) and then the refetchInterval only continues to poll while the returned data is e.g. not "success". When it's finished, the query goes back to disabled and polling stops
rising-crimson
rising-crimson3y ago
refetchInterval doesn't run on disabled queries, no, but you can enable it conditionally
eager-peach
eager-peachOP3y ago
Got it! I think I can work with that, thanks guys! ❤️

Did you find this page helpful?