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

index.js

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