MCPcopy Index your code
hub / github.com/electric-sql/pglite / useLiveQueryImpl

Function useLiveQueryImpl

packages/pglite-react/src/hooks.ts:20–99  ·  view source on GitHub ↗
(
  query: string | LiveQuery<T> | Promise<LiveQuery<T>>,
  params: unknown[] | undefined | null,
  key?: string,
)

Source from the content-addressed store, hash-verified

18}
19
20function useLiveQueryImpl<T = { [key: string]: unknown }>(
21 query: string | LiveQuery<T> | Promise<LiveQuery<T>>,
22 params: unknown[] | undefined | null,
23 key?: string,
24): Omit<LiveQueryResults<T>, 'affectedRows'> | undefined {
25 const db = usePGlite()
26 const paramsRef = useRef(params)
27 const liveQueryRef = useRef<LiveQuery<T> | undefined>(undefined)
28 let liveQuery: LiveQuery<T> | undefined
29 let liveQueryChanged = false
30 if (!(typeof query === 'string') && !(query instanceof Promise)) {
31 liveQuery = query
32 liveQueryChanged = liveQueryRef.current !== liveQuery
33 liveQueryRef.current = liveQuery
34 }
35 const [results, setResults] = useState<LiveQueryResults<T> | undefined>(
36 liveQuery?.initialResults,
37 )
38
39 let currentParams = paramsRef.current
40 if (!paramsEqual(paramsRef.current, params)) {
41 paramsRef.current = params
42 currentParams = params
43 }
44
45 /* eslint-disable @eslint-react/hooks-extra/no-direct-set-state-in-use-effect */
46 useEffect(() => {
47 let cancelled = false
48 const cb = (results: LiveQueryResults<T>) => {
49 if (cancelled) return
50 setResults(results)
51 }
52 if (typeof query === 'string') {
53 const ret =
54 key !== undefined
55 ? db.live.incrementalQuery<T>(query, currentParams, key, cb)
56 : db.live.query<T>(query, currentParams, cb)
57
58 return () => {
59 cancelled = true
60 ret.then(({ unsubscribe }) => unsubscribe())
61 }
62 } else if (query instanceof Promise) {
63 query.then((liveQuery) => {
64 if (cancelled) return
65 liveQueryRef.current = liveQuery
66 setResults(liveQuery.initialResults)
67 liveQuery.subscribe(cb)
68 })
69 return () => {
70 cancelled = true
71 liveQueryRef.current?.unsubscribe(cb)
72 }
73 } else if (liveQuery) {
74 setResults(liveQuery.initialResults)
75 liveQuery.subscribe(cb)
76 return () => {
77 cancelled = true

Callers 3

useLiveQueryFunction · 0.70
hooks.tsFile · 0.70
useLiveIncrementalQueryFunction · 0.70

Calls 4

paramsEqualFunction · 0.85
incrementalQueryMethod · 0.80
queryMethod · 0.65
unsubscribeFunction · 0.50

Tested by

no test coverage detected