Open History to see the last commit
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
19}
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}
30β
31export function useReactQueryConfig(config = {}) {
32 Object.assign(defaultConfig, config)
33}
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
297}
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 }
405}
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 )
431}
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 }]
489}
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
507}
508β
509export function useIsFetching() {
510 const queries = _useQueries()
511β
512 return React.useMemo(() => queries.some(query => query.isFetching), [queries])
513}
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 }
533}
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 )
546}
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]
583}
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
596}
597β
598function sortedStringify(obj) {
599 return JSON.stringify(obj, sortedStringifyReplacer)
600}
601β
602function isObject(a) {
603 return a && a !== null && typeof a === 'object'
604}
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
615}
616β
617function isOnline() {
618 if (typeof navigator.onLine !== 'undefined') {
619 return navigator.onLine
620 }
621β
622 return true
623}
624β
625function useGetLatest(obj) {
626 const ref = React.useRef()
627 ref.current = obj
628β
629 return React.useCallback(() => ref.current, [])
630}
631β
632function functionalUpdate(updater, old) {
633 return typeof updater === 'function' ? updater(old) : updater
634}