`setQueryData()` should be persisted too, right? #6310
Describe the bug#
I'm using the new experimental_createPersister like this:
import { experimental_createPersister, type AsyncStorage } from "@tanstack/query-persist-client-core";
import { get, set, del, createStore, type UseStore } from "idb-keyval";
function newIdbStorage(idbStore: UseStore): AsyncStorage {
return {
getItem: async (key) => await get(key, idbStore),
setItem: async (key, value) => await set(key, value, idbStore),
removeItem: async (key) => await del(key, idbStore),
};
}
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
gcTime: 1000 * 30, // 30 seconds
persister: experimental_createPersister({
storage: newIdbStorage(createStore("db_name", "store_name")),
maxAge: 1000 * 60 * 60 * 12, // 12 hours
}),
},
},
});
But I just found out that if I call
const SetPlayerTeam = (team: Team) => {
queryClient.setQueryData<Player>(
['player', team.playerId],
(old) => old && { ...old, team }
);
};
the in memory cache works (the team is added to player) but there is not setItem() call for this last queryClient.setQueryData(). If I reload the page the team is not on player anymore (unless I invalidate the player manually).
I think this is wrong, because this change should be persisted too.
I'll create a reproduction if you think it might be useful.
How often does this bug happen?#
Every time
Platform#
Chrome.
Tanstack Query adapter#
svelte-query
TanStack Query version#
5.4.3
TypeScript version#
5
Additional context#
I'm using:
"@tanstack/eslint-plugin-query": "5.0.5",
"@tanstack/query-persist-client-core": "5.4.3",
"@tanstack/svelte-query": "5.4.3",
"@tanstack/svelte-query-devtools": "5.4.3",TkDodo added labelspackage: query-persist-client-core
I agree that it would be important if persistence can be somehow implemented with
setQueryData. Right now, the flow breaks when you're using opportunistic updates withuseMutationqueries.one problem I'm seeing is that
getQueryDataalso doesn't read from the persisted storage, and it really can't, because persistence can be async, andgetQueryDatais sync.why does the flow "break" with optimistic updates though?
Oh and what about if data comes into the cache via hydration 🤔
My mistake about the useMutation flow. I didn't have
onSettledinvalidate queries to force a refetch in the background. 😅 Doing that makes it work fine 👍🏻For storing the data, if we have a
persisterset up on the client level, we could easily hook it up. Or acceptpersisteras a prop, but i would like to avoid that.The problem is that
createPersistercurrently returns a function. But we only need a small portion of it. We could introduce a flag to the returned function to control the flow and execute only a portion of it. Or return different structure fromcreatePersisterwith few functions that would be picked up in different contexts.As for
getting the data, we would need to introduce anotherasyncversion of it that will do similar checks as current persister fn. If cache is empty, try to get from storage if configured, otherwise get from cache (this includes hydrated data). Ofc this will work on-demand, and would not attempt to restore automatically on app load.Just some general input as I'm testing out the new
createPersisterin my app. Benchmarking before and after switching, the results are staggering - in some cases 8000x improvement in terms of speed! However I am experiencing some issues all tied to the fact thatsetQueryDatanot updating - here are some of them:- I'm using
setQueryDatato add local-only metadata to certain results. This metadata is NOT available on the server side, and so refetching it would essentially remove the metadata and mess up the state of my data. - My data (it's a timeline of sort) is stored "permanently" on disk (
qcTime=Infinity,staleTime=Infinity) locally, and I can't just refetch several thousands queries to update the state. I patch things in the timeline as they come in usingsetQueryData. Additionally, it's not a guarantee that the original request would even work anymore if I were to invalidate or refetch several days, weeks or months old data. - I use
setQueryDatato clean up and optimize my timeline data, and this data is also no longer persisted. - I have some background jobs (outside of React context) that change data using
setQueryDatawhich correctly rerenders the components with the new data, but that data is no longer updated in the store which is problematic.
I suppose I'm also abusing the library a bit and it was not really meant for all these use cases though, but I do believe that some of them are valid reasons where
setQueryDatashould also persist.As for
getting the data, we would need to introduce anotherasyncversion of it that will do similar checks as current persister fn. If cache is empty, try to get from storage if configured, otherwise get from cache (this includes hydrated data). Ofc this will work on-demand, and would not attempt to restore automatically on app load.I think this sounds like a fair solution although I also feel like that could cause issues/bugs if someone for example uses
queryClient.getQueryCache().getAll()to "get all" cached queries but it doesn't actually "get all" because some might not be loaded yet withuseQuerysince they're persisted.. if it loaded everything when app was restored that would be avoided however. If an async function was added to work around this then people would have to know to use this over the other one when using the new persister.- I'm using
There are a couple of things that lead me to think having
setQueryDatawrite to the persister as well is not a good idea:- we can't make reads work
reads from the cache are synchronous, so
getQueryDatawill never be able to return data from the cache. If we are thinking about a separate getter that somehow can do this, why not a setter as well?- it will only work when the persister is defined globally
If you have
useQuerywith a persister passed touseQuerydirectly,setQueryDatawill not see it, so it won't write to the disk. That's an inconsistency I wouldn't expect.- the queryClient is just a wrapper around the queryCache
it doesn't do anything - you can just as well call
queryClient.getQueryCache()and operate on the raw methods instead. By adding this special thing tosetQueryDataandensureQueryData, we break that statement.- there are other ways to write to the cache
For example, you can use
hydrateto write data to the cache. Would we need to cover them all, or is this just aboutqueryClient.setQueryData()
Imo, being an "ad-hoc" persister was always part of the plan. Async reads (= running the queryFn) would try to read from the storage first, unless there is data already in the cache. It's like "fallback" data. If we get data into the in-memory cache by other means, we don't need to lookup the fallback.
Maybe it's conceptually wrong that the
queryFn"writes data back" to the storage after it runs - maybe this should happen on a more global level, with a queryCache subscription ? Then, all writes would be synced back, but reads would only read lazily. @DamianOsipiuk what do you think ?Well, the cool thing about current solution is that you can add
persisterdirectly touseQueryand itjust works™️.We could potentially hook to the cache to store it in persister, but I'm kinda worried about adding a listener for every query, if users decide to do it this way.
queryFnis deduped, while listeners are not. It would work for global persister, but not for the local ones.Maybe we should just force users to set up persister globally with
filterFnforqueryKey, or disablingpersisterfor specificuseQuerycalls. Then we could hook listener on the cache. But ergonomics of this solution is kinda worse than the current one.We could potentially expose async
persistQueryandrestoreQueryfromcreatePersisterthat would takequeryKeyandqueryClientand expect users to call those methods when needed. Ex aftersetQuery.It would work for global persister, but not for the local ones.
can you elaborate why there's a difference between global and local ones? The global one is just a default value setting - it's functionally equivalent imo to passing
persistermanually to all useQuery callsbut I'm kinda worried about adding a listener for every query
PersistQueryClientdoes that, too, and I think it would still be properly deduped because we would listen only to events that put data into the cache. We could also throttle the writes if necessary.We could potentially expose async persistQuery and restoreQuery from createPersister that would take queryKey and queryClient and expect users to call those methods when needed. Ex after setQuery.
yeah that's an option. We could also just expose the auto-write subscribe hook and then let users decide which way they want ?
can you elaborate why there's a difference between global and local ones
For global persister you call
createPersisteronly once when instantiatingqueryClientso we could add only one listener.For
per-queryusers couldcreatePersisteron each render resulting in thousands of listeners. And I would like to prevent users shooting their foot byusing it wrong.I beleive that
PersistQueryClientworks differently as listener creation is out of user reach? I might be wrong though.For per-query users could createPersister on each render resulting in thousands of listeners.
right, I see what you mean. It would have to become a hook like
userPersisterso that we could use component lifecycle, but then it becomes framework specific again. Even on global level, we would need a way to unsubscribe, which usually requires lifecycle methods. That's why thePersistQueryClientProviderexists, too 🤔I beleive that PersistQueryClient works differently as listener creation is out of user reach? I might be wrong though.
It sets up a subscription for writes and eagerly restores data. We basically only want the writes, and keep the restores lazily.
I would love to be able to
setQueryDatato the query cache one way or another. The query cache is so much more performant than the client cache.For us who work on multiple-page applications, the client cache can get quite big in some cases and loads on every navigation. Having the cache only be loaded when needed would be great for us!
We are considering just using something like https://github.com/epicweb-dev/cachified , but it would defeat the point of using tanstack query.
@TorbjornHoltmon cachified seems an amazing idea!
Any updates on this please ? - With VueJS, I think the only way to persist data between reload/page-refresh is using
createPersisterfunction, and add apersisterin theuseQuerycall (since there's nothing likePersistQueryClientwrapper present in VueJS, please correct me if I am wrong) and then the setQueryData not writing the mutation updates to the persisted data kinda forces us to invalidate the cache every time after any mutation to show correct results which is troublesome in terms of making those API calls again and again in the application. So havingsetQueryDatato update the persisted cache data would be a great addition 🙏 .@jai2201 There is a draft MR that splits original implementation to be more granular, allowing you to use returned utilities in user land. Also adding additional utilities for convenience.
It needs some tests and docs though.
https://github.com/TanStack/query/pull/8062
return { persisterFn, persistQuery, retrieveQuery, persisterGc, persisterRestoreAll, }It sounds like there is still some work being done here to make
setQueryDatapersist properly, but Im wondering what a decent short-term solution might look like? Would you just manually persist to storage (indexedDB, localStorage, etc) everywhere you invokesetQueryData? I suppose you could alternatively make a wrapper hook around setQueryData that would handle this. Something likefunction useSetQuery() { const qc = useQueryClient() function setQueryData(// queryClient.setQueryData args would be mirrored here) { qc.setQueryData(...) // invoke persister setter manually here } return setQueryData }@lancej1022 Thankfully you can install the update with
npm i https://pkg.pr.new/@tanstack/query-persist-client-core@8062then you only need to change one importimport { experimental_createQueryPersister } from "@tanstack/query-persist-client-core"It seems to be working for me with this approach
let clientQueryClientSingleton: QueryClient | undefined = undefined let hasRestoredQueries = false function newIdbStorage(idbStore: UseStore) { return { getItem: async (key: IDBValidKey) => await get(key, idbStore), setItem: async (key: IDBValidKey, value: any) => { console.log(`setting ${key}`) return await set(key, value, idbStore) }, removeItem: async (key: IDBValidKey) => await del(key, idbStore), entries: async () => { return await entries(idbStore) } } } export const persister = experimental_createQueryPersister({ // @ts-ignore storage: newIdbStorage(createStore("name", "qc")), serialize: SuperJSON.serialize, prefix: "v1", deserialize: SuperJSON.deserialize, maxAge: Number.POSITIVE_INFINITY }) export const createQueryClient = () => new QueryClient({ defaultOptions: { queries: { // @ts-ignore persister: persister.persisterFn, retry: true, experimental_prefetchInRender: false, networkMode: "offlineFirst", gcTime: 1000 * 60 * 60 * 24, // 24 hours staleTime: 60 * 1000, refetchOnReconnect: false, refetchOnMount: false, refetchOnWindowFocus: true } } }) export const getQueryClient = () => { // biome-ignore lint/suspicious/noAssignInExpressions: <explanation> const queryClient = (clientQueryClientSingleton ??= createQueryClient()) if (!hasRestoredQueries) { hasRestoredQueries = true // @ts-ignore void persister.persisterRestoreAll(queryClient) console.log("Restored") } return queryClient }Then in my mutation I do this:
queryClient.setQueryData( ["cat"] data.resultValue ) const catQuery = queryClient.getQueryCache().find({ queryKey:["cat"], exact: true }) persister.persistQuery(catQuery).then(console.log)I'm not totally sure how any of this works so it could all be very wrong
A question to Contributors and someone who knows a lot about how Tanstack actually works. Until any official solution goes live, do you think this workaround is viable?
import { experimental_createPersister } from '@tanstack/react-query-persist-client'; export const storage = new MMKV(); const clientStorage = { setItem: (key: string, value: string) => { storage.set(key, value); }, getItem: (key: string) => { const value = storage.getString(key); return value === undefined ? null : value; }, removeItem: (key: string) => { storage.delete(key); }, }; const persister = experimental_createPersister({ storage: clientStorage, maxAge: 5 * TimeService.minute, }); someMethod() { queryClient.setQueryData(cacheKey, (queryData: unknown | undefined) => { // some business logic here // ........ return updatedCacheItem; }); persistQuery(cacheKey); } const persistQuery = (cacheKey: string[]) => { const state = queryClient.getQueryState(cacheKey); const queryHash = JSON.stringify(cacheKey); const storageKey = `tanstack-query-${queryHash}`; storage.set( storageKey, JSON.stringify({ state: state, queryKey: cacheKey, queryHash: queryHash, buster: '', }), ); };persistQuerycode is taken from https://github.com/TanStack/query/pull/8062/files#diff-49e8b295893ae938f8fc349ec5c9d037944289d845c64c2ed9e38f9bbd63eba1So the idea is that after
queryClient.setQueryDataI'm manually saving the result to the persist storage. From my tests this works and in our case it's mostly used when the app is offline and there is no way to invalidate the actual query.Thanks!
with #8062 you can now invoke persist manually with
persistQueryByKey, so this should work:function useSetQuery() { const qc = useQueryClient() function setQueryData(// queryClient.setQueryData args would be mirrored here) { qc.setQueryData(...) // invoke persister setter manually here } return setQueryData }TkDodo closed this
I ended up with this solution using
persistQueryByKey:import { experimental_createQueryPersister } from "@tanstack/query-persist-client-core"; import { QueryPersister, useQueryClient } from "@tanstack/react-query"; export const usePersister = () => { const queryClient = useQueryClient(); const persister = experimental_createQueryPersister({ storage: window.localStorage, maxAge: 1000 * 60 * 60 * 24 * 30, }); const setPersistentQueryData = (cacheKey: string[], newValue: any): void => { queryClient.setQueryData(cacheKey, newValue); persister.persistQueryByKey(cacheKey, queryClient as any); }; return { persister: persister.persisterFn as unknown as QueryPersister<any, any, any>, setPersistentQueryData }; };May not be the best, but I thought I'd share a complete example.
@TkDodo @Minding000 I’m trying to understand how this is expected to work with setQueriesData. Let’s say I have multiple queries that differ only by params:
['items', 'lists', { param1: 'a' }] ['items', 'lists', { param2: 'b' }]Both queries can contain overlapping items. When I update a single item via a mutation, I want all queries under
['items', 'lists']to update. So when you update them usingqueryClient.setQueriesData({ queryKey: ['items', 'lists'] }, updaterFn)persistQueryByKey won't work to update the persisted cache. How is this intended to be handled? Is there a recommended approach for updating multiple related queries that share a partial key?How is this intended to be handled? Is there a recommended approach for updating multiple related queries that share a partial key?
setQueriesDatareturnsArray<[QueryKey, TQueryFnData | undefined]>, containing all QueryKeys it matched. You can then loop over that and callpersistQueryByKeyfor each one of them.
Sign in to join this conversation.
hmm, good question. Right now, the persister is just a wrapper around the
queryFn. If thequeryFndoesn't run, we don't persist. And withsetQueryData, it doesn't run ... 🤔@DamianOsipiuk what are your thoughts here?