TanStackT
TanStackโ€ข3y agoโ€ข
24 replies
exclusive-coral

Persistence: how to call save only when `data` is updated?

I'm using persistQueryClient function to restore, subscribe and save query cache to async storage.
What I noticed in the sources is that persistQueryClientSubscribe subscribes to all changes in query cache and calls persistQueryClientSave in callback:
queryClient
    .getQueryCache()
    .subscribe(() => {
      persistQueryClientSave(props)
    })

It means that persistQueryClientSave is called every time when e.g. query status change or new useQuery hook is mounted on new screen. Basically in my app persistQueryClientSave is called a lot and even with throttling enabled it still feels that sometimes it is called unnecessarily.

Please correct me if I'm wrong with this example:
I have query with query key ["users"] and I have useQuery hooks for this key mounted both in screen A and screen B. They both have staleTime set to 1 hour.
Screen A is mounted and it fetches data successfully. Then I go to screen B where data is not refetched because it's still fresh. So the data is still exactly the same but persistQueryClientSave is called because subscriber is triggered by observerAdded or observerOptionsUpdated events.

So my question is - is it possible to call persistQueryClientSave only if data in any query is updated? Maybe there is a way to subscribe only for data changes? Or maybe I'm missing something and it works like that for a reason?
I was also thinking about calling persistQueryClientSave in onSuccess callback in default options. Although I don't really like this solution because it will break if onSuccess is overwritten and it also is called multiple times if more useQuery hooks are mounted for single query.

Thanks for any help and suggestions here ๐Ÿ™
Was this page helpful?