Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useQueries.ts

55 lines1.6 KB

1import React from 'react'
2​
3import { notifyManager } from '../core/notifyManager'
4import { QueriesObserver } from '../core/queriesObserver'
5import { useQueryClient } from './QueryClientProvider'
6import { UseQueryOptions, UseQueryResult } from './types'
7​
8export function useQueries(queries: UseQueryOptions[]): UseQueryResult[] {
9 const mountedRef = React.useRef(false)
10 const [, forceUpdate] = React.useState(0)
11​
12 const queryClient = useQueryClient()
13​
14 const defaultedQueries = queries.map(options => {
15 const defaultedOptions = queryClient.defaultQueryObserverOptions(options)
16​
17 // Make sure the results are already in fetching state before subscribing or updating options
18 defaultedOptions.optimisticResults = true
19​
20 return defaultedOptions
21 })
22​
23 const obsRef = React.useRef<QueriesObserver>()
24​
25 if (!obsRef.current) {
26 obsRef.current = new QueriesObserver(queryClient, defaultedQueries)
27 }
28​
29 const result = obsRef.current.getOptimisticResult(defaultedQueries)
30​
31 React.useEffect(() => {
32 mountedRef.current = true
33​
34 const unsubscribe = obsRef.current!.subscribe(
35 notifyManager.batchCalls(() => {
36 if (mountedRef.current) {
37 forceUpdate(x => x + 1)
38 }
39 })
40 )
41​
42 return () => {
43 mountedRef.current = false
44 unsubscribe()
45 }
46 }, [])
47​
48 React.useEffect(() => {
49 // Do not notify on updates because of changes in the options because
50 // these changes should already be reflected in the optimistic result.
51 obsRef.current!.setQueries(defaultedQueries, { listeners: false })
52 }, [defaultedQueries])
53​
54 return result