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

index.js

748 lines17.2 KB

1import React from 'react'
2​
3export let queries = []
4const cancelledError = {}
5export let globalStateListeners = []
6let uid = 0
7const configContext = React.createContext()
8​
9// Focus revalidate
10let eventsBinded = false
11if (typeof window !== 'undefined' && !eventsBinded) {
12 const revalidate = () => {
13 const { refetchAllOnWindowFocus } = defaultConfig
14 if (refetchAllOnWindowFocus && isDocumentVisible() && isOnline())
15 refetchAllQueries()
16 }
17 window.addEventListener('visibilitychange', revalidate, false)
18 window.addEventListener('focus', revalidate, false)
19 eventsBinded = true
21​
22let defaultConfig = {
23 retry: 3,
24 retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
25 staleTime: 0,
26 cacheTime: 5 * 60 * 1000,
27 refetchAllOnWindowFocus: true,
28 refetchInterval: false,
29 suspense: false,
30 queryKeySerializerFn: defaultQueryKeySerializerFn,
32​
33export function ReactQueryConfigProvider({ config, children }) {
34 let configContextValue = React.useContext(configContext)
35​
36 const newConfig = React.useMemo(
37 () => ({
38 ...(configContextValue || defaultConfig),
39 ...config,
40 }),
41 [config, configContextValue]
42 )
43​
44 if (!configContextValue) {
45 defaultConfig = newConfig
46 }
47​
48 return (
49 <configContext.Provider value={newConfig}>
50 {children}
51 </configContext.Provider>
52 )
54​
55function useConfigContext() {
56 return React.useContext(configContext) || defaultConfig
58​
59function makeQuery(options) {
60 let query = {
61 ...options,
62 pageVariables: [],
63 instances: [],
64 state: {
65 error: null,
66 isFetching: false,
67 isFetchingMore: false,
68 canFetchMore: false,
69 failureCount: 0,
70 isCached: false,
71 isStale: true,
72 data: options.config.paginated ? [] : null,
73 },
74 // promise: null,
75 // staleTimeout: null,
76 // cacheTimeout: null,
77 // cancelled: null,
78 }
79​
80 query.setState = updater => {
81 query.state = functionalUpdate(updater, query.state)
82 query.instances.forEach(instance => {
83 instance.onStateUpdate(query.state)
84 })
85 globalStateListeners.forEach(d => d())
86 }
87​
88 query.subscribe = instance => {
89 let found = query.instances.find(d => d.id === instance.id)
90​
91 if (found) {
92 Object.assign(found, instance)
93 } else {
94 found = instance
95 query.instances.push(instance)
96 }
97​
98 // Mark as active
99 query.setState(old => {
100 return {
101 ...old,
102 isInactive: false,
103 }
104 })
105​
106 // Cancel garbage collection
107 clearTimeout(query.cacheTimeout)
108​
109 // Mark the query as not cancelled
110 query.cancelled = null
111​
112 // Return the unsubscribe function
113 return () => {
114 query.instances = query.instances.filter(d => d.id !== instance.id)
115​
116 if (!query.instances.length) {
117 // Cancel any side-effects
118 query.cancelled = cancelledError
119​
120 // Mark as inactive
121 query.setState(old => {
122 return {
123 ...old,
124 isInactive: true,
125 }
126 })
127​
128 // Schedule garbage collection
129 query.cacheTimeout = setTimeout(
130 () => {
131 queries.splice(queries.findIndex(d => d === query), 1)
132 globalStateListeners.forEach(d => d())
133 },
134 query.state.isCached ? query.config.cacheTime : 0
135 )
136 }
137 }
138 }
139​
140 // Set up the fetch function
141 const tryFetchQueryPages = async pageVariables => {
142 try {
143 // Perform the query
144 const data = await Promise.all(
145 pageVariables.map(variables => query.queryFn(variables))
146 )
147​
148 if (query.cancelled) throw query.cancelled
149​
150 return data
151 } catch (error) {
152 if (query.cancelled) throw query.cancelled
153​
154 // If we fail, increase the failureCount
155 query.setState(old => {
156 return {
157 ...old,
158 failureCount: old.failureCount + 1,
159 }
160 })
161​
162 // Do we need to retry the request?
163 if (
164 // Only retry if the document is visible
165 query.config.retry === true ||
166 query.state.failureCount < query.config.retry
167 ) {
168 if (!isDocumentVisible()) {
169 return new Promise(r => {})
170 }
171​
172 // Determine the retryDelay
173 const delay = functionalUpdate(
174 query.config.retryDelay,
175 query.state.failureCount
176 )
177​
178 // Return a new promise with the retry
179 return new Promise((resolve, reject) => {
180 // Keep track of the retry timeout
181 setTimeout(async () => {
182 if (query.cancelled) return reject(query.cancelled)
183​
184 try {
185 const data = await tryFetchQueryPages(pageVariables)
186 if (query.cancelled) return reject(query.cancelled)
187 resolve(data)
188 } catch (error) {
189 if (query.cancelled) return reject(query.cancelled)
190 reject(error)
191 }
192 }, delay)
193 })
194 }
195​
196 throw error
197 }
198 }
199​
200 query.fetch = async ({
201 variables = query.config.paginated && query.state.isCached
202 ? query.pageVariables
203 : query.variables,
204 force,
205 isFetchMore,
206 } = {}) => {
207 // Don't refetch fresh queries without force
208 if (!query.queryHash || (!query.state.isStale && !force)) {
209 return
210 }
211​
212 // Create a new promise for the query cache if necessary
213 if (!query.promise) {
214 query.promise = (async () => {
215 // If there are any retries pending for this query, kill them
216 query.cancelled = null
217​
218 const cleanup = () => {
219 delete query.promise
220​
221 // Schedule a fresh invalidation, always!
222 clearTimeout(query.staleTimeout)
223​
224 query.staleTimeout = setTimeout(() => {
225 if (query) {
226 query.setState(old => {
227 return {
228 ...old,
229 isStale: true,
230 }
231 })
232 }
233 }, query.config.staleTime)
234​
235 query.setState(old => {
236 return {
237 ...old,
238 isFetching: false,
239 isFetchingMore: false,
240 }
241 })
242 }
243​
244 try {
245 // Set up the query refreshing state
246 query.setState(old => {
247 return {
248 ...old,
249 error: null,
250 isFetching: true,
251 isFetchingMore: isFetchMore,
252 failureCount: 0,
253 }
254 })
255​
256 variables =
257 query.config.paginated && query.state.isCached && !isFetchMore
258 ? variables
259 : [variables]
260​
261 // Try to fetch
262 let data = await tryFetchQueryPages(variables)
263​
264 // If we are paginating, and this is the first query or a fetch more
265 // query, then store the variables in the pageVariables
266 if (
267 query.config.paginated &&
268 (isFetchMore || !query.state.isCached)
269 ) {
270 query.pageVariables.push(variables[0])
271 }
272​
273 // Set data and mark it as cached
274 query.setState(old => {
275 data = query.config.paginated
276 ? isFetchMore
277 ? [...old.data, data[0]]
278 : data
279 : data[0]
280​
281 return {
282 ...old,
283 data,
284 isCached: true,
285 isStale: false,
286 ...(query.config.paginated && {
287 canFetchMore: query.config.getCanFetchMore(
288 data[data.length - 1],
289 data
290 ),
291 }),
292 }
293 })
294​
295 query.instances.forEach(
296 instance =>
297 instance.onSuccess && instance.onSuccess(query.state.data)
298 )
299​
300 cleanup()
301​
302 return data
303 } catch (error) {
304 // As long as it's not a cancelled retry
305 cleanup()
306​
307 if (error !== query.cancelled) {
308 // Store the error
309 query.setState(old => {
310 return {
311 ...old,
312 error,
313 isCached: false,
314 isStale: true,
315 }
316 })
317​
318 query.instances.forEach(
319 instance => instance.onError && instance.onError(error)
320 )
321​
322 throw error
323 }
324 }
325 })()
326 }
327​
328 return query.promise
329 }
330​
331 query.setData = updater =>
332 query.setState(old => ({
333 ...old,
334 data: functionalUpdate(updater, old.data),
335 }))
336​
337 return query
339​
340export function useQuery(queryKey, queryFn, config = {}) {
341 const isMountedRef = React.useRef(false)
342 const instanceIdRef = React.useRef(uid++)
343 const instanceId = instanceIdRef.current
344​
345 config = {
346 ...useConfigContext(),
347 ...config,
348 }
349​
350 const { manual } = config
351​
352 const [
353 queryHash,
354 queryGroup,
355 variablesHash,
356 variables,
357 ] = config.queryKeySerializerFn(queryKey)
358​
359 let query = queries.find(query => query.queryHash === queryHash)
360​
361 let wasPrefetched
362​
363 if (query) {
364 wasPrefetched = query.config.prefetch
365 query.config = config
366 if (!isMountedRef.current) {
367 query.config.prefetch = wasPrefetched
368 }
369 query.queryFn = queryFn
370 } else {
371 query = makeQuery({
372 queryHash,
373 queryGroup,
374 variablesHash,
375 variables,
376 config,
377 queryFn,
378 })
379 queries.push(query)
380 }
381​
382 React.useEffect(() => {
383 if (config.refetchInterval && !query.refetchInterval) {
384 query.refetchInterval = setInterval(query.fetch, config.refetchInterval)
385​
386 return () => {
387 clearInterval(query.refetchInterval)
388 query.refetchInterval = null
389 }
390 }
391 }, [config.refetchInterval, query])
392​
393 const [state, setState] = React.useState(query.state)
394​
395 const onStateUpdate = React.useCallback(newState => setState(newState), [])
396 const getLatestOnError = useGetLatest(config.onError)
397 const getLatestOnSuccess = useGetLatest(config.onSuccess)
398​
399 React.useEffect(() => {
400 const unsubscribeFromQuery = query.subscribe({
401 id: instanceId,
402 onStateUpdate,
403 onSuccess: data => getLatestOnSuccess() && getLatestOnSuccess()(data),
404 onError: err => getLatestOnError() && getLatestOnError()(err),
405 })
406 return unsubscribeFromQuery
407 }, [getLatestOnError, getLatestOnSuccess, instanceId, onStateUpdate, query])
408​
409 const isLoading = !state.isCached && query.state.isFetching
410 const refetch = query.fetch
411 const setData = query.setData
412​
413 const fetchMore = React.useCallback(
414 config.paginated
415 ? paginationVariables =>
416 query.fetch({
417 variables: paginationVariables,
418 force: true,
419 isFetchMore: true,
420 })
421 : undefined,
422 [query]
423 )
424​
425 const getLatestManual = useGetLatest(manual)
426​
427 React.useEffect(() => {
428 if (getLatestManual()) {
429 return
430 }
431​
432 if (config.suspense) {
433 if (isMountedRef.current || wasPrefetched) {
434 return
435 }
436 }
437​
438 const runRefetch = async () => {
439 try {
440 await query.fetch()
441 } catch (err) {
442 console.error(err)
443 // Swallow this error. Don't rethrow it into a render function
444 }
445 }
446​
447 runRefetch()
448 }, [config.suspense, getLatestManual, query, wasPrefetched])
449​
450 React.useEffect(() => {
451 isMountedRef.current = true
452 }, [])
453​
454 if (config.suspense) {
455 if (state.error) {
456 throw state.error
457 }
458 if (!state.isCached) {
459 throw query.fetch()
460 }
461 }
462​
463 return {
464 ...state,
465 isLoading,
466 refetch,
467 fetchMore,
468 setData,
469 }
471​
472export async function prefetchQuery(queryKey, queryFn, config = {}) {
473 config = {
474 ...defaultConfig,
475 ...config,
476 prefetch: true,
477 }
478​
479 const [
480 queryHash,
481 queryGroup,
482 variablesHash,
483 variables,
484 ] = defaultConfig.queryKeySerializerFn(queryKey)
485​
486 // If we're prefetching, use the queryFn to make the fetch call
487​
488 let query = queries.find(query => query.queryHash === queryHash)
489​
490 if (query) {
491 if (!config.force) {
492 return
493 }
494 query.config = config
495 query.queryFn = queryFn
496 } else {
497 query = makeQuery({
498 queryHash,
499 queryGroup,
500 variablesHash,
501 variables,
502 config,
503 queryFn,
504 })
505 queries.push(query)
506 }
507​
508 // Trigger a query subscription with one-time unique id
509 const unsubscribeFromQuery = query.subscribe({
510 id: uid++,
511 onStateUpdate: () => {},
512 })
513​
514 // Trigger a fetch and return the promise
515 try {
516 return await query.fetch({ force: config.force })
517 } finally {
518 // Since this is not a hook, upsubscribe after we're done
519 unsubscribeFromQuery()
520 }
522​
523export async function refetchQuery(queryKey, config = {}) {
524 const [
525 ,
526 queryGroup,
527 variablesHash,
528 variables,
529 ] = defaultConfig.queryKeySerializerFn(queryKey)
530​
531 // If we're simply refetching an existing query, then go find them
532 // and call their fetch functions
533​
534 if (!queryGroup) {
535 return
536 }
537​
538 return Promise.all(
539 queries.map(async query => {
540 if (query.queryGroup !== queryGroup) {
541 return
542 }
543​
544 if (variables === false && query.variablesHash) {
545 return
546 }
547​
548 if (variablesHash && query.variablesHash !== variablesHash) {
549 return
550 }
551​
552 await query.fetch({ force: config.force })
553 })
554 )
556​
557export function useMutation(
558 mutationFn,
559 { refetchQueries, refetchQueriesOnFailure } = {}
560) {
561 const [data, setData] = React.useState(null)
562 const [error, setError] = React.useState(null)
563 const [isLoading, setIsLoading] = React.useState(false)
564 const mutationFnRef = React.useRef()
565 mutationFnRef.current = mutationFn
566​
567 const mutate = React.useCallback(
568 async (variables, { updateQuery, waitForRefetchQueries = false } = {}) => {
569 setIsLoading(true)
570 setError(null)
571​
572 const doRefetchQueries = async () => {
573 const refetchPromises = refetchQueries.map(queryKey =>
574 refetchQuery(queryKey, { force: true })
575 )
576 if (waitForRefetchQueries) {
577 await Promise.all(refetchPromises)
578 }
579 }
580​
581 try {
582 const res = await mutationFnRef.current(variables)
583 setData(res)
584​
585 if (updateQuery) {
586 setQueryData(updateQuery, res, { shouldRefetch: false })
587 }
588​
589 if (refetchQueries) {
590 try {
591 await doRefetchQueries()
592 } catch (err) {
593 console.error(err)
594 // Swallow this error since it is a side-effect
595 }
596 }
597​
598 setIsLoading(false)
599​
600 return res
601 } catch (error) {
602 setError(error)
603​
604 if (refetchQueriesOnFailure) {
605 await doRefetchQueries()
606 }
607​
608 setIsLoading(false)
609 throw error
610 }
611 },
612 [refetchQueriesOnFailure, refetchQueries]
613 )
614​
615 return [mutate, { data, isLoading, error }]
617​
618export function useIsFetching() {
619 const [state, setState] = React.useState({ queries })
620​
621 React.useEffect(() => {
622 const fn = () => {
623 setState({ queries })
624 }
625​
626 globalStateListeners.push(fn)
627​
628 return () => {
629 globalStateListeners = globalStateListeners.filter(d => d !== fn)
630 }
631 }, [])
632​
633 return React.useMemo(() => state.queries.some(query => query.isFetching), [
634 state.queries,
635 ])
637​
638export function setQueryData(
639 userQueryKey,
640 updater,
641 { shouldRefetch = true } = {}
642) {
643 const [queryHash] = defaultConfig.queryKeySerializerFn(userQueryKey)
644​
645 if (!queryHash) {
646 return
647 }
648​
649 const query = queries.find(d => d.queryHash === queryHash)
650​
651 query.setData(updater)
652​
653 if (shouldRefetch) {
654 return refetchQuery(userQueryKey)
655 }
657​
658export async function refetchAllQueries({
659 includeInactive,
660 force = includeInactive,
661} = {}) {
662 return Promise.all(
663 queries.map(async query => {
664 if (query.instances.length || includeInactive) {
665 return query.fetch({ force })
666 }
667 })
668 )
670​
671function defaultQueryKeySerializerFn(queryKey) {
672 if (!queryKey) {
673 return []
674 }
675​
676 if (typeof queryKey === 'function') {
677 try {
678 return defaultQueryKeySerializerFn(queryKey())
679 } catch {
680 return []
681 }
682 }
683​
684 if (Array.isArray(queryKey)) {
685 let [id, variables] = queryKey
686 const variablesIsObject = isObject(variables)
687​
688 if (typeof id !== 'string' || (variables && !variablesIsObject)) {
689 console.warn('Tuple queryKey:', queryKey)
690 throw new Error(
691 `Invalid query key tuple type: [${typeof id}, and ${typeof variables}]`
692 )
693 }
694​
695 const variablesHash = variablesIsObject ? stableStringify(variables) : ''
696​
697 return [
698 `${id}${variablesHash ? `_${variablesHash}}` : ''}`,
699 id,
700 variablesHash,
701 variables,
702 ]
703 }
704​
705 return [queryKey, queryKey]
707​
708function stableStringifyReplacer(_, value) {
709 return isObject(value)
710 ? Object.assign(
711 {},
712 ...Object.keys(value)
713 .sort()
714 .map(key => ({
715 [key]: value[key],
716 }))
717 )
718 : value
720​
721export function stableStringify(obj) {
722 return JSON.stringify(obj, stableStringifyReplacer)
724​
725function isObject(a) {
726 return a && typeof a === 'object'
728​
729function isDocumentVisible() {
730 return document.visibilityState === undefined
731 || document.visibilityState === 'visible'
732 || document.visibilityState === 'prerender'
734​
735function isOnline() {
736 return navigator.onLine === undefined || navigator.onLine
738​
739function useGetLatest(obj) {
740 const ref = React.useRef()
741 ref.current = obj
742​
743 return React.useCallback(() => ref.current, [])
745​
746function functionalUpdate(updater, old) {
747 return typeof updater === 'function' ? updater(old) : updater