MCPcopy Create free account
hub / github.com/TanStack/query / retrieveQuery

Function retrieveQuery

packages/query-persist-client-core/src/createPersister.ts:206–251  ·  view source on GitHub ↗

* Reads the persisted data of a query from storage. Expired, busted, or unreadable entries are * removed instead. * @param queryHash - The hash of the query to read. * @param afterRestoreMacroTask - Scheduled with the persisted query after it is restored. * @returns A promise that resolv

(
    queryHash: string,
    afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,
  )

Source from the content-addressed store, hash-verified

204 * restored.
205 */
206 async function retrieveQuery<T>(
207 queryHash: string,
208 afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,
209 ) {
210 if (storage != null) {
211 const storageKey = `${prefix}-${queryHash}`
212 try {
213 const storedData = await storage.getItem(storageKey)
214 if (storedData != null) {
215 let persistedQuery: PersistedQuery
216 try {
217 persistedQuery = await deserialize(storedData)
218 if (!isValidPersistedQuery(persistedQuery)) {
219 throw new Error('Invalid persisted query')
220 }
221 } catch {
222 await storage.removeItem(storageKey)
223 return
224 }
225
226 if (isExpiredOrBusted(persistedQuery)) {
227 await storage.removeItem(storageKey)
228 } else {
229 if (afterRestoreMacroTask) {
230 // Just after restoring we want to get fresh data from the server if it's stale
231 notifyManager.schedule(() =>
232 afterRestoreMacroTask(persistedQuery),
233 )
234 }
235 // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves
236 return persistedQuery.state.data as T
237 }
238 }
239 } catch (err) {
240 if (process.env.NODE_ENV === 'development') {
241 console.error(err)
242 console.warn(
243 'Encountered an error attempting to restore query cache from persisted location.',
244 )
245 }
246 await storage.removeItem(storageKey)
247 }
248 }
249
250 return
251 }
252
253 /**
254 * Persists the query with the given key, if it exists in the client's cache.

Callers 1

persisterFnFunction · 0.85

Calls 3

isValidPersistedQueryFunction · 0.85
isExpiredOrBustedFunction · 0.85
removeItemMethod · 0.80

Tested by

no test coverage detected