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 queryKeySerializerFn: defaultQueryKeySerializerFn,
30}
31β
32export function useReactQueryConfig(config = {}) {
33 Object.assign(defaultConfig, config)
34}
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
298}
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 }
409}
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 )
440}
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 }]
498}
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
516}
517β
518export function useIsFetching() {
519 const queries = _useQueries()
520β
521 return React.useMemo(() => queries.some(query => query.isFetching), [queries])
522}
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 }
542}
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 )
555}
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]
592}
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
605}
606β
607export function stableStringify(obj) {
608 return JSON.stringify(obj, stableStringifyReplacer)
609}
610β
611function isObject(a) {
612 return a && a !== null && typeof a === 'object'
613}
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
624}
625β
626function isOnline() {
627 if (typeof navigator.onLine !== 'undefined') {
628 return navigator.onLine
629 }
630β
631 return true
632}
633β
634function useGetLatest(obj) {
635 const ref = React.useRef()
636 ref.current = obj
637β
638 return React.useCallback(() => ref.current, [])
639}
640β
641function functionalUpdate(updater, old) {
642 return typeof updater === 'function' ? updater(old) : updater
643}