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

index.js

643 lines14.7 KB

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