T
TanStack•3y ago
like-gold

Update refetchInterval

Hello! App that I'm working on is presumably working in multiple browser tabs/windows, I'm using queries with refetchInterval in few places, and interval is set to 3 minutes. This causes an issue where apps in different tabs seems to be out of sync, eg. first tab is refetching data at 10:00, 10:03, and so on, second tab is refetching data at 10:01, 10:04 and so on. Is it possible to define refetchInterval as function, and provide custom logic which would allow to calculate different interval till first refetch, and after first refetch, upadte given interval, so all windows/tabs would trigger refetch at same time? For example: first tab triggers first fetch at 10:00, next refetch should happen at 10:03 - refetchInterval should never change as it is always exactly 3 minutes second tab triggers first fetch at 10:01, next refetch should happen at 10:03 - refetchInterval is set to 2 minutes, and after first refetch it is updated to 3 minutes I couldn't find such information in docs and by quickly looking at the source code it appears that it is possible, but I'm looking for confirmation.
5 Replies
deep-jade
deep-jade•3y ago
refetchInterval also accepts a function, so you can add some custom logic in there
like-gold
like-goldOP•3y ago
yes, this is what I've mentioned - my question is when this function will get called? Will it get called after every refetch?
deep-jade
deep-jade•3y ago
ah yeah sorry I read too fast. Based on the useQuery docs:
If set to a function, the function will be executed with the latest data and query to compute a frequency
I would expect it to be called at every refetch in order to compute the next interval. I think the code confirms it (at least in the latest v4 tag): updateTimers() is called on every query update (https://github.com/TanStack/query/blob/v4.29.19/packages/query-core/src/queryObserver.ts#L677) and that function computes the next interval and applies it: https://github.com/TanStack/query/blob/v4.29.19/packages/query-core/src/queryObserver.ts#L398 You would have to build the logic to synchronize the tabs yourself though.
GitHub
query/packages/query-core/src/queryObserver.ts at v4.29.19 · TanSta...
🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query. - query/packages/query-core/src/queryObs...
fair-rose
fair-rose•3y ago
it's also updated when options are set - so basically every render 🙂 to see if the resulting interval changed (you could closure over a prop or something). interval will only be updated if you return a different value
like-gold
like-goldOP•3y ago
Great, thanks!

Did you find this page helpful?