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