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({
36 queryHash,
37 queryGroup,
38 variablesHash,
39 variables,
40 config,
41 queryFn,
42}) {
43 let query = {
44 queryHash,
45 queryGroup,
46 variablesHash,
47 variables,
48 promise: null,
49 previousDelay: 0,
50 staleTimeout: null,
51 cacheTimeout: null,
52 cancelled: null,
53 state: {
54 data: config.paginated ? [] : null,
55 error: null,
56 isFetching: false,
57 isFetchingMore: false,
58 canFetchMore: false,
59 failureCount: 0,
60 isCached: false,
61 isStale: true,
62 },
63 pageVariables: [],
64 instances: [],
65 }
66β
67 query.setState = updater => {
68 query.state = typeof updater === 'function' ? updater(query.state) : updater
69 query.instances.forEach(instance => {
70 instance.onStateUpdate(query.state)
71 })
72 globalStateListeners.forEach(d => d())
73 }
74β
75 query.subscribe = instance => {
76 let found = query.instances.find(d => d.id === instance.id)
77β
78 if (found) {
79 Object.assign(found, instance)
80 } else {
81 found = instance
82 query.instances.push(instance)
83 }
84β
85 // Mark as inactive
86 query.setState(old => {
87 return {
88 ...old,
89 isInactive: false,
90 }
91 })
92β
93 // Cancel garbage collection
94 clearTimeout(query.cacheTimeout)
95β
96 // Mark the query as not cancelled
97 query.cancelled = null
98β
99 // Return the unsubscribe function
100 return () => {
101 query.instances = query.instances.filter(d => d.id !== instance.id)
102β
103 if (!query.instances.length) {
104 // Cancel any side-effects
105 query.cancelled = cancelledError
106β
107 // Mark as inactive
108 query.setState(old => {
109 return {
110 ...old,
111 isInactive: true,
112 }
113 })
114β
115 // Schedule garbage collection
116 query.cacheTimeout = setTimeout(
117 () => {
118 queries.splice(queries.findIndex(d => d === query), 1)
119 globalStateListeners.forEach(d => d())
120 },
121 query.state.isCached ? config.cacheTime : 0
122 )
123 }
124 }
125 }
126β
127 // Set up the fetch function
128 const tryFetchQueryPages = async pageVariables => {
129 try {
130 // Perform the query
131 const data = await Promise.all(
132 pageVariables.map(variables => queryFn(variables))
133 )
134β
135 if (query.cancelled) throw query.cancelled
136β
137 return data
138 } catch (error) {
139 if (query.cancelled) throw query.cancelled
140β
141 // If we fail, increase the failureCount
142 query.setState(old => {
143 return {
144 ...old,
145 failureCount: old.failureCount + 1,
146 }
147 })
148β
149 // Do we need to retry the request?
150 if (
151 // Only retry if the document is visible
152 config.retry === true ||
153 query.state.failureCount < config.retry
154 ) {
155 if (!isDocumentVisible()) {
156 return new Promise(r => {})
157 }
158β
159 // Determine the retryDelay
160 const delay =
161 typeof config.retryDelay === 'function'
162 ? config.retryDelay(query.state.failureCount)
163 : config.retryDelay
164β
165 // Return a new promise with the retry
166 return new Promise((resolve, reject) => {
167 // Keep track of the retry timeout
168 setTimeout(async () => {
169 if (query.cancelled) return reject(query.cancelled)
170β
171 try {
172 const data = await tryFetchQueryPages(pageVariables)
173 if (query.cancelled) return reject(query.cancelled)
174 resolve(data)
175 } catch (error) {
176 if (query.cancelled) return reject(query.cancelled)
177 reject(error)
178 }
179 }, delay)
180 })
181 }
182β
183 throw error
184 }
185 }
186β
187 query.fetch = async ({
188 variables = config.paginated && query.state.isCached
189 ? query.pageVariables
190 : query.variables,
191 force,
192 isFetchMore,
193 } = {}) => {
194 // Don't refetch fresh queries without force
195 if (!query.state.isStale && !force) {
196 return
197 }
198β
199 // Create a new promise for the query cache if necessary
200 if (!query.promise) {
201 query.promise = (async () => {
202 // If there are any retries pending for this query, kill them
203 query.cancelled = null
204β
205 try {
206 // Set up the query refreshing state
207 query.setState(old => {
208 return {
209 ...old,
210 error: null,
211 isFetching: true,
212 isFetchingMore: isFetchMore,
213 failureCount: 0,
214 }
215 })
216β
217 variables =
218 config.paginated && query.state.isCached && !isFetchMore
219 ? variables
220 : [variables]
221β
222 // Try to fetch
223 let data = await tryFetchQueryPages(variables)
224β
225 // If we are paginating, and this is the first query or a fetch more
226 // query, then store the variables in the pageVariables
227 if (config.paginated && (isFetchMore || !query.state.isCached)) {
228 query.pageVariables.push(variables[0])
229 }
230β
231 // Set data and mark it as cached
232 query.setState(old => {
233 data = config.paginated
234 ? isFetchMore
235 ? [...old.data, data[0]]
236 : data
237 : data[0]
238β
239 return {
240 ...old,
241 data,
242 isCached: true,
243 isStale: false,
244 ...(config.paginated && {
245 canFetchMore: config.getCanFetchMore(
246 data[data.length - 1],
247 data
248 ),
249 }),
250 }
251 })
252β
253 return data
254 } catch (error) {
255 // As long as it's not a cancelled retry
256 if (error !== query.cancelled) {
257 // Store the error
258 query.setState(old => {
259 return {
260 ...old,
261 error,
262 isCached: false,
263 isStale: true,
264 }
265 })
266β
267 throw error
268 }
269 } finally {
270 // Schedule a fresh invalidation, always!
271 clearTimeout(query.staleTimeout)
272β
273 query.staleTimeout = setTimeout(() => {
274 if (query) {
275 query.setState(old => {
276 return {
277 ...old,
278 isStale: true,
279 }
280 })
281 }
282 }, config.staleTime)
283β
284 query.setState(old => {
285 return {
286 ...old,
287 isFetching: false,
288 isFetchingMore: false,
289 }
290 })
291 delete query.promise
292 }
293 })()
294 }
295β
296 return query.promise
297 }
298β
299 query.setData = updater =>
300 query.setState(old => ({
301 ...old,
302 data: typeof updater === 'function' ? updater(old.data) : updater,
303 }))
304β
305 return query
306}
307β
308export function useQuery(queryKey, queryFn, config = {}) {
309 const instanceIdRef = React.useRef(uid++)
310 const instanceId = instanceIdRef.current
311β
312 config = {
313 ...defaultConfig,
314 ...config,
315 }
316β
317 const { manual } = config
318β
319 const [queryHash, queryGroup, variablesHash, variables] = getQueryInfo(
320 queryKey
321 )
322β
323 let query = queries.find(query => query.queryHash === queryHash)
324β
325 if (query) {
326 query.config = config
327 query.queryFn = queryFn
328 } else {
329 query = makeQuery({
330 queryHash,
331 queryGroup,
332 variablesHash,
333 variables,
334 config,
335 queryFn,
336 })
337 queries.push(query)
338 }
339β
340 React.useEffect(() => {
341 if (config.refetchInterval && !query.refetchInterval) {
342 query.refetchInterval = setInterval(query.fetch, config.refetchInterval)
343β
344 return () => {
345 clearInterval(query.refetchInterval)
346 query.refetchInterval = null
347 }
348 }
349 }, [config.refetchInterval, query])
350β
351 const [state, setState] = React.useState(query.state)
352β
353 const onStateUpdate = React.useCallback(newState => setState(newState), [])
354β
355 React.useEffect(() => {
356 const unsubscribeFromQuery = query.subscribe({
357 id: instanceId,
358 onStateUpdate,
359 })
360 return unsubscribeFromQuery
361 }, [instanceId, onStateUpdate, query])
362β
363 const isLoading = !queryHash || manual ? false : state.isCached ? false : true
364 const refetch = query.fetch
365 const setData = query.setData
366β
367 const fetchMore = React.useCallback(
368 config.paginated
369 ? variables => query.fetch({ variables, force: true, isFetchMore: true })
370 : undefined,
371 [query]
372 )
373β
374 const getLatestManual = useGetLatest(manual)
375 const isMountedRef = React.useRef(false)
376β
377 React.useEffect(() => {
378 isMountedRef.current = true
379 }, [])
380β
381 React.useEffect(() => {
382 if (getLatestManual() || (config.suspense && !isMountedRef.current)) {
383 return
384 }
385β
386 const runRefetch = async () => {
387 try {
388 await query.fetch()
389 } catch (err) {
390 console.error(err)
391 // Swallow this error. Don't rethrow it into a render function
392 }
393 }
394β
395 runRefetch()
396 }, [config.suspense, getLatestManual, query, queryHash])
397β
398 if (config.suspense) {
399 if (state.error) {
400 throw state.error
401 }
402 if (!state.isCached) {
403 throw query.fetch()
404 }
405 }
406β
407 return {
408 ...state,
409 isLoading,
410 refetch,
411 fetchMore,
412 setData,
413 }
414}
415β
416export async function refetchQuery(userQueryKey, { force } = {}) {
417 const [, queryGroup, variablesHash, variables] = getQueryInfo(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] = getQueryInfo(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 getQueryInfo(queryKey) {
558 if (!queryKey) {
559 return []
560 }
561β
562 if (typeof queryKey === 'function') {
563 try {
564 return getQueryInfo(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 (process.env.NODE_ENV !== 'production') {
575 if (typeof id !== 'string' || (variables && !variablesIsObject)) {
576 console.warn('Tuple queryKey:', queryKey)
577 throw new Error(
578 `Tuple query keys must be of type [string, object]. You have passed [${typeof id}, and ${typeof variables}]`
579 )
580 }
581 }
582β
583 const variablesHash = variablesIsObject ? sortedStringify(variables) : ''
584β
585 return [
586 `${id}${variablesHash ? `_${variablesHash}}` : ''}`,
587 id,
588 variablesHash,
589 variables,
590 ]
591 }
592β
593 return [queryKey, queryKey]
594}
595β
596function sortedStringifyReplacer(_, value) {
597 return isObject(value)
598 ? Object.assign(
599 {},
600 ...Object.keys(value)
601 .sort((keyA, keyB) => (keyA > keyB ? 1 : keyB > keyA ? -1 : 0))
602 .map(key => ({
603 [key]: value[key],
604 }))
605 )
606 : value
607}
608β
609function sortedStringify(obj) {
610 return JSON.stringify(obj, sortedStringifyReplacer)
611}
612β
613function isObject(a) {
614 return a && a !== null && typeof a === 'object'
615}
616β
617function isDocumentVisible() {
618 if (typeof document.visibilityState !== 'undefined') {
619 return (
620 document.visibilityState === 'visible' ||
621 document.visibilityState === 'prerender'
622 )
623 }
624 // always assume it's visible
625 return true
626}
627β
628function isOnline() {
629 if (typeof navigator.onLine !== 'undefined') {
630 return navigator.onLine
631 }
632 // always assume it's online
633 return true
634}
635β
636function useGetLatest(obj) {
637 const ref = React.useRef()
638 ref.current = obj
639β
640 return React.useCallback(() => ref.current, [])
641}