TanStackT
TanStackโ€ข2y agoโ€ข
7 replies
faint-white

App-level polling with react-query

Hello,

I am dealing with asynchronous API.
In other words, I have mutation (POST/PUT) requests that will trigger async jobs in the back-end.
These job can take 10-20s to complete, and in order to keep my front-end synchronized I am doing conditional polling.

const { isSuccess } = useMyMutation({})

const myQuery = useGetMyData({
    refetchInterval: query => {
      const isFresh = isSuccess && isDataFresh(query.state.data)
      return isFresh ? false : 5000
    }
  })


This code is fine, but the polling is done only at component-level, because I need to check that the mutation is successful and rely on some data comparison to determine if the polling should be processed.

Unfortunately, whenever I unmount my component, the polling will stop and other components that are observer of the useGetMyData will not poll.

Idea:
I was thinking of implementing in-house app-level polling like:
useMyMutation({
  onSuccess: () => {
    appPolling.add({
      interval: 5000,
      process: () => {
        invalidateUseMyDataQuery()
      },
      stopOn: <MyDataType>(data) => {
        isDataFresh(query.state.data)
      }
    })
  }
})


The code seems a bit magic, probably it will be different to properly handle callback functions and typesafety.
This solution is still not perfect, because the user can send the mutation and navigate to another route before the
onSuccess
is triggered.

Do you think there are better/easier way to do app-level polling ?

Thanks ๐Ÿ™‚
Was this page helpful?