Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

queryCache.js

600 lines14.9 KB

1import React from 'react'
2import {
3 isServer,
4 functionalUpdate,
5 cancelledError,
6 isDocumentVisible,
7 statusLoading,
8 statusSuccess,
9 statusError,
10 getQueryArgs,
11 deepIncludes,
12 noop,
13} from './utils'
14import { defaultConfigRef } from './config'
15​
16export const queryCache = makeQueryCache()
17​
18export const queryCacheContext = React.createContext(queryCache)
19​
20export const queryCaches = [queryCache]
21​
22export function useQueryCache() {
23 return React.useContext(queryCacheContext)
25​
26export function ReactQueryCacheProvider({ queryCache, children }) {
27 const cache = React.useMemo(() => queryCache || makeQueryCache(), [
28 queryCache,
29 ])
30​
31 React.useEffect(() => {
32 queryCaches.push(cache)
33​
34 return () => {
35 // remove the cache from the active list
36 const i = queryCaches.indexOf(cache)
37 if (i >= 0) {
38 queryCaches.splice(i, 1)
39 }
40 // if the cache was created by us, we need to tear it down
41 if (queryCache == null) {
42 cache.clear()
43 }
44 }
45 }, [cache, queryCache])
46​
47 return (
48 <queryCacheContext.Provider value={cache}>
49 {children}
50 </queryCacheContext.Provider>
51 )
53​
54const actionInit = {}
55const actionFailed = {}
56const actionMarkStale = {}
57const actionMarkGC = {}
58const actionFetch = {}
59const actionSuccess = {}
60const actionError = {}
61const actionSetState = {}
62​
63export function makeQueryCache() {
64 const listeners = []
65​
66 const cache = {
67 queries: {},
68 isFetching: 0,
69 }
70​
71 const notifyGlobalListeners = () => {
72 cache.isFetching = Object.values(cache.queries).reduce(
73 (acc, query) => (query.state.isFetching ? acc + 1 : acc),
74 0
75 )
76 listeners.forEach(d => d(cache))
77 }
78​
79 cache.subscribe = cb => {
80 listeners.push(cb)
81 return () => {
82 listeners.splice(listeners.indexOf(cb), 1)
83 }
84 }
85​
86 cache.clear = () => {
87 Object.values(cache.queries).forEach(query => query.clear())
88 cache.queries = {}
89 notifyGlobalListeners()
90 }
91​
92 const findQueries = (predicate, { exact } = {}) => {
93 if (typeof predicate !== 'function') {
94 const [
95 queryHash,
96 queryKey,
97 ] = defaultConfigRef.current.queryKeySerializerFn(predicate)
98 predicate = d =>
99 exact ? d.queryHash === queryHash : deepIncludes(d.queryKey, queryKey)
100 }
101​
102 return Object.values(cache.queries).filter(predicate)
103 }
104​
105 cache.getQueries = findQueries
106​
107 cache.getQuery = queryKey => findQueries(queryKey, { exact: true })[0]
108​
109 cache.getQueryData = queryKey => cache.getQuery(queryKey)?.state.data
110​
111 cache.removeQueries = (predicate, { exact } = {}) => {
112 const foundQueries = findQueries(predicate, { exact })
113​
114 foundQueries.forEach(query => {
115 clearTimeout(query.staleTimeout)
116 delete cache.queries[query.queryHash]
117 })
118​
119 if (foundQueries.length) {
120 notifyGlobalListeners()
121 }
122 }
123​
124 cache.cancelQueries = (predicate, { exact } = {}) => {
125 const foundQueries = findQueries(predicate, { exact })
126​
127 foundQueries.forEach(query => {
128 query.cancel()
129 })
130​
131 if (foundQueries.length) {
132 notifyGlobalListeners()
133 }
134 }
135​
136 cache.refetchQueries = async (
137 predicate,
138 { exact, throwOnError, force } = {}
139 ) => {
140 const foundQueries =
141 predicate === true
142 ? Object.values(cache.queries)
143 : findQueries(predicate, { exact })
144​
145 try {
146 return await Promise.all(
147 foundQueries.map(query => query.fetch({ force }))
148 )
149 } catch (err) {
150 if (throwOnError) {
151 throw err
152 }
153 }
154 }
155​
156 cache._buildQuery = (userQueryKey, queryVariables, queryFn, config) => {
157 let [queryHash, queryKey] = config.queryKeySerializerFn(userQueryKey)
158​
159 let query = cache.queries[queryHash]
160​
161 if (query) {
162 Object.assign(query, { queryVariables, queryFn })
163 query.config = { ...query.config, ...config }
164 } else {
165 query = makeQuery({
166 cache,
167 queryKey,
168 queryHash,
169 queryVariables,
170 queryFn,
171 config,
172 })
173​
174 // If the query started with data, schedule
175 // a stale timeout
176 if (!isServer && query.state.data) {
177 query.scheduleStaleTimeout()
178​
179 // Simulate a query healing process
180 query.heal()
181 // Schedule for garbage collection in case
182 // nothing subscribes to this query
183 query.scheduleGarbageCollection()
184 }
185​
186 if (query.queryHash) {
187 if (!isServer) {
188 cache.queries[queryHash] = query
189 // Here, we setTimeout so as to not trigger
190 // any setState's in parent components in the
191 // middle of the render phase.
192 setTimeout(() => {
193 notifyGlobalListeners()
194 })
195 }
196 }
197 }
198​
199 return query
200 }
201​
202 cache.prefetchQuery = async (...args) => {
203 let [
204 queryKey,
205 queryVariables,
206 queryFn,
207 { force, ...config },
208 ] = getQueryArgs(args)
209​
210 config = {
211 ...defaultConfigRef.current,
212 ...config,
213 }
214​
215 const query = cache._buildQuery(queryKey, queryVariables, queryFn, config)
216​
217 // Don't prefetch queries that are fresh, unless force is passed
218 if (query.state.isStale || force) {
219 // Trigger a fetch and return the promise
220 try {
221 const res = await query.fetch({ force })
222 query.wasPrefetched = true
223 return res
224 } catch (err) {
225 if (config.throwOnError) {
226 throw err
227 }
228 }
229 }
230​
231 return query.state.data
232 }
233​
234 cache.setQueryData = (queryKey, updater, { exact, ...config } = {}) => {
235 let queries = findQueries(queryKey, { exact })
236​
237 if (!queries.length && typeof queryKey !== 'function') {
238 queries = [
239 cache._buildQuery(queryKey, undefined, () => Promise.resolve(), {
240 ...defaultConfigRef.current,
241 ...config,
242 }),
243 ]
244 }
245​
246 queries.forEach(d => d.setData(updater))
247 }
248​
249 function makeQuery(options) {
250 const queryCache = options.cache
251 const reducer = options.config.queryReducer || defaultQueryReducer
252​
253 const noQueryHash = typeof options.queryHash === 'undefined'
254​
255 const initialData =
256 typeof options.config.initialData === 'function'
257 ? options.config.initialData()
258 : options.config.initialData
259​
260 const hasInitialData = typeof initialData !== 'undefined'
261​
262 const isStale = noQueryHash ? true : !hasInitialData
263​
264 const manual = options.config.manual
265​
266 const initialStatus =
267 noQueryHash || manual || hasInitialData ? statusSuccess : statusLoading
268​
269 const query = {
270 ...options,
271 instances: [],
272 state: reducer(undefined, {
273 type: actionInit,
274 initialStatus,
275 initialData,
276 hasInitialData,
277 isStale,
278 manual,
279 }),
280 }
281​
282 const dispatch = action => {
283 query.state = reducer(query.state, action)
284 query.instances.forEach(d => d.onStateUpdate(query.state))
285 notifyGlobalListeners()
286 }
287​
288 query.scheduleStaleTimeout = () => {
289 if (query.config.staleTime === Infinity) {
290 return
291 }
292 query.staleTimeout = setTimeout(() => {
293 if (queryCache.getQuery(query.queryKey)) {
294 dispatch({ type: actionMarkStale })
295 }
296 }, query.config.staleTime)
297 }
298​
299 query.scheduleGarbageCollection = () => {
300 if (query.config.cacheTime === Infinity) {
301 return
302 }
303 dispatch({ type: actionMarkGC })
304 query.cacheTimeout = setTimeout(
305 () => {
306 cache.removeQueries(
307 d =>
308 d.state.markedForGarbageCollection &&
309 d.queryHash === query.queryHash
310 )
311 },
312 typeof query.state.data === 'undefined' &&
313 query.state.status !== 'error'
314 ? 0
315 : query.config.cacheTime
316 )
317 }
318​
319 query.heal = () => {
320 // Stop the query from being garbage collected
321 clearTimeout(query.cacheTimeout)
322​
323 // Mark the query as not cancelled
324 query.cancelled = null
325 }
326​
327 query.cancel = () => {
328 query.cancelled = cancelledError
329​
330 if (query.cancelPromises) {
331 query.cancelPromises()
332 }
333​
334 delete query.promise
335​
336 notifyGlobalListeners()
337 }
338​
339 query.updateInstance = instance => {
340 let found = query.instances.find(d => d.id === instance.id)
341​
342 if (found) {
343 Object.assign(found, instance)
344 } else {
345 found = {
346 onStateUpdate: noop,
347 ...instance,
348 }
349 query.instances.push(instance)
350 }
351 }
352​
353 query.subscribe = instanceId => {
354 query.heal()
355​
356 // Return the unsubscribe function
357 return () => {
358 query.instances = query.instances.filter(d => d.id !== instanceId)
359​
360 if (!query.instances.length) {
361 query.cancel()
362​
363 // Schedule garbage collection
364 query.scheduleGarbageCollection()
365 }
366 }
367 }
368​
369 // Set up the fetch function
370 const tryFetchData = async (queryFn, ...args) => {
371 try {
372 // Perform the query
373 const promise = queryFn(...query.config.queryFnParamsFilter(args))
374​
375 query.cancelPromises = () => promise.cancel?.()
376​
377 const data = await promise
378 delete query.shouldContinueRetryOnFocus
379​
380 delete query.cancelPromises
381 if (query.cancelled) throw query.cancelled
382​
383 return data
384 } catch (error) {
385 delete query.cancelPromises
386 if (query.cancelled) throw query.cancelled
387​
388 // If we fail, increase the failureCount
389 dispatch({ type: actionFailed })
390​
391 // Do we need to retry the request?
392 if (
393 query.config.retry === true ||
394 query.state.failureCount <= query.config.retry ||
395 (typeof query.config.retry === 'function' &&
396 query.config.retry(query.state.failureCount, error))
397 ) {
398 // Only retry if the document is visible
399 if (!isDocumentVisible()) {
400 // set this flag to continue fetch retries on focus
401 query.shouldContinueRetryOnFocus = true
402 return new Promise(noop)
403 }
404​
405 delete query.shouldContinueRetryOnFocus
406​
407 // Determine the retryDelay
408 const delay = functionalUpdate(
409 query.config.retryDelay,
410 query.state.failureCount
411 )
412​
413 // Return a new promise with the retry
414 return await new Promise((resolve, reject) => {
415 // Keep track of the retry timeout
416 setTimeout(async () => {
417 if (query.cancelled) return reject(query.cancelled)
418​
419 try {
420 const data = await tryFetchData(queryFn, ...args)
421 if (query.cancelled) return reject(query.cancelled)
422 resolve(data)
423 } catch (error) {
424 if (query.cancelled) return reject(query.cancelled)
425 reject(error)
426 }
427 }, delay)
428 })
429 }
430​
431 throw error
432 }
433 }
434​
435 query.fetch = async ({ force, __queryFn = query.queryFn } = {}) => {
436 // Don't refetch fresh queries that don't have a queryHash
437​
438 if (!query.queryHash || (!query.state.isStale && !force)) {
439 return
440 }
441​
442 // Create a new promise for the query cache if necessary
443 if (!query.promise) {
444 query.promise = (async () => {
445 // If there are any retries pending for this query, kill them
446 query.cancelled = null
447​
448 const callbackInstances = [...query.instances]
449​
450 if (query.wasSuspended) {
451 callbackInstances.unshift(query.suspenseInstance)
452 }
453​
454 try {
455 // Set up the query refreshing state
456 dispatch({ type: actionFetch })
457​
458 // Try to fetch
459 let data = await tryFetchData(
460 __queryFn,
461 ...query.queryKey,
462 ...query.queryVariables
463 )
464​
465 query.setData(old =>
466 query.config.isDataEqual(old, data) ? old : data
467 )
468​
469 callbackInstances.forEach(
470 instance =>
471 instance.onSuccess && instance.onSuccess(query.state.data)
472 )
473​
474 callbackInstances.forEach(
475 instance =>
476 instance.onSettled && instance.onSettled(query.state.data, null)
477 )
478​
479 delete query.promise
480​
481 return data
482 } catch (error) {
483 dispatch({
484 type: actionError,
485 cancelled: error === query.cancelled,
486 error,
487 })
488​
489 delete query.promise
490​
491 if (error !== query.cancelled) {
492 callbackInstances.forEach(
493 instance => instance.onError && instance.onError(error)
494 )
495​
496 callbackInstances.forEach(
497 instance =>
498 instance.onSettled && instance.onSettled(undefined, error)
499 )
500​
501 throw error
502 }
503 }
504 })()
505 }
506​
507 return query.promise
508 }
509​
510 query.setState = updater => dispatch({ type: actionSetState, updater })
511​
512 query.setData = updater => {
513 // Set data and mark it as cached
514 dispatch({ type: actionSuccess, updater })
515​
516 // Schedule a fresh invalidation!
517 clearTimeout(query.staleTimeout)
518 query.scheduleStaleTimeout()
519 }
520​
521 query.clear = () => {
522 clearTimeout(query.staleTimeout)
523 clearTimeout(query.cacheTimeout)
524 query.cancel()
525 }
526​
527 return query
528 }
529​
530 return cache
532​
533export function defaultQueryReducer(state, action) {
534 switch (action.type) {
535 case actionInit:
536 return {
537 status: action.initialStatus,
538 error: null,
539 isFetching:
540 action.hasInitialData || action.manual
541 ? false
542 : action.initialStatus === 'loading',
543 canFetchMore: false,
544 failureCount: 0,
545 isStale: action.isStale,
546 markedForGarbageCollection: false,
547 data: action.initialData,
548 updatedAt: action.hasInitialData ? Date.now() : 0,
549 }
550 case actionFailed:
551 return {
552 ...state,
553 failureCount: state.failureCount + 1,
554 }
555 case actionMarkStale:
556 return {
557 ...state,
558 isStale: true,
559 }
560 case actionMarkGC: {
561 return {
562 ...state,
563 markedForGarbageCollection: true,
564 }
565 }
566 case actionFetch:
567 return {
568 ...state,
569 status: state.status === statusError ? statusLoading : state.status,
570 isFetching: true,
571 failureCount: 0,
572 }
573 case actionSuccess:
574 return {
575 ...state,
576 status: statusSuccess,
577 data: functionalUpdate(action.updater, state.data),
578 error: null,
579 isStale: false,
580 isFetching: false,
581 canFetchMore: action.canFetchMore,
582 updatedAt: Date.now(),
583 failureCount: 0,
584 }
585 case actionError:
586 return {
587 ...state,
588 isFetching: false,
589 isStale: true,
590 ...(!action.cancelled && {
591 status: statusError,
592 error: action.error,
593 }),
594 }
595 case actionSetState:
596 return functionalUpdate(action.updater, state)
597 default:
598 throw new Error()
599 }