-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
useBaseQuery.js
47 lines (36 loc) · 1.12 KB
/
useBaseQuery.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import React from 'react'
//
import { useQueryCache } from './ReactQueryCacheProvider'
import { useMountedCallback } from './utils'
export function useBaseQuery(queryKey, config = {}) {
// Make a rerender function
const rerender = useMountedCallback(React.useState()[1])
// Get the query cache
const queryCache = useQueryCache()
// Build the query for use
const query = queryCache.buildQuery(queryKey, config)
// Create a query instance ref
const instanceRef = React.useRef()
// Subscribe to the query when the subscribe function changes
React.useEffect(() => {
instanceRef.current = query.subscribe(() => rerender({}))
// Unsubscribe when things change
return instanceRef.current.unsubscribe
}, [query, rerender])
// Always update the config
React.useEffect(() => {
instanceRef.current.updateConfig(config)
})
// Run the instance when the query or enabled change
React.useEffect(() => {
if (config.enabled && query) {
// Just for change detection
}
instanceRef.current.run()
}, [config.enabled, query])
return {
...query,
...query.state,
query,
}
}