react-querylong-pollingtanstackreact-query

RefetchInterval, and QueryKey Changing, will this cause two network requests?


Really need some help understanding the nuances and effects of how refetchInterval, and queryKeys interact with each other.

Currently, I have a UI that is stuck on loading state. I suspect it is because of a refetchInterval setting in my query client options. My theory is that, because one of my hooks takes about 5 seconds to respond, and my refetch interval is 2 seconds, we are always fetching, and never returning a loaded state.

I have two hooks. One, useGetOffset, returns an incremented value mostly on every call. Sometimes it doesn't.

So lets say, my refetch interval is 2 seconds. Every two seconds, useGetOffset will return 1, 2, 3, 4.

I use the offset value in another hook, lets say useGetBilling, so the offset value is part of useGetBilling's query key.

Since I have a global refetchInterval of 2 seconds, every two seconds, useGetOffset, and useGetBilling should be refetched.

now, because useGetOffset value changes, does this mean: useGetBilling will be called twice?

Once, when the useGetOffset value changes, and second, when the refetchInterval is up?

I imagine the timeline to be:

time: 0, useFetchInterval returns 0, useGetBilling(0)

time: 2, useFetchInterval returns 1, we call useGetBilling with he new key, and we call useGetBilling(0) due to refetch interval?

At the end of the day, I actually just want the refetch interval to apply to all my queries, but if some queries take longer than 2.5 seconds, I'd like to pause the refetchInterval.


Solution

  • My theory is that, because one of my hooks takes about 5 seconds to respond, and my refetch interval is 2 seconds, we are always fetching, and never returning a loaded state.

    That’s not how it works. The refetchInterval is only started after you get a successful response. So if you start a fetch at timestamp 0, get a response back at timestamp 5000 and have an interval set to 2000, the next time the interval triggers will be at 7000.