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)
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 )
53}
54β
55function useConfigContext() {
56 return React.useContext(configContext) || defaultConfig
57}
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
338}
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 }
470}
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 }
521}
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 )
555}
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 }]
616}
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 ])
636}
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 }
656}
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 )
669}
670β
671export function clearQueryCache() {
672 queries.length = 0;
673}
674β
675function defaultQueryKeySerializerFn(queryKey) {
676 if (!queryKey) {
677 return []
678 }
679β
680 if (typeof queryKey === 'function') {
681 try {
682 return defaultQueryKeySerializerFn(queryKey())
683 } catch {
684 return []
685 }
686 }
687β
688 if (Array.isArray(queryKey)) {
689 let [id, variables] = queryKey
690 const variablesIsObject = isObject(variables)
691β
692 if (typeof id !== 'string' || (variables && !variablesIsObject)) {
693 console.warn('Tuple queryKey:', queryKey)
694 throw new Error(
695 `Invalid query key tuple type: [${typeof id}, and ${typeof variables}]`
696 )
697 }
698β
699 const variablesHash = variablesIsObject ? stableStringify(variables) : ''
700β
701 return [
702 `${id}${variablesHash ? `_${variablesHash}}` : ''}`,
703 id,
704 variablesHash,
705 variables,
706 ]
707 }
708β
709 return [queryKey, queryKey]
710}
711β
712function stableStringifyReplacer(_, value) {
713 return isObject(value)
714 ? Object.assign(
715 {},
716 ...Object.keys(value)
717 .sort()
718 .map(key => ({
719 [key]: value[key],
720 }))
721 )
722 : value
723}
724β
725export function stableStringify(obj) {
726 return JSON.stringify(obj, stableStringifyReplacer)
727}
728β
729function isObject(a) {
730 return a && typeof a === 'object'
731}
732β
733function isDocumentVisible() {
734 return document.visibilityState === undefined
735 || document.visibilityState === 'visible'
736 || document.visibilityState === 'prerender'
737}
738β
739function isOnline() {
740 return navigator.onLine === undefined || navigator.onLine
741}
742β
743function useGetLatest(obj) {
744 const ref = React.useRef()
745 ref.current = obj
746β
747 return React.useCallback(() => ref.current, [])
748}
749β
750function functionalUpdate(updater, old) {
751 return typeof updater === 'function' ? updater(old) : updater
752}