diff --git a/packages/pglite-react/src/hooks.ts b/packages/pglite-react/src/hooks.ts index 73d9ced6..92f29855 100644 --- a/packages/pglite-react/src/hooks.ts +++ b/packages/pglite-react/src/hooks.ts @@ -18,7 +18,11 @@ function paramsEqual( } function useLiveQueryImpl( - query: string | LiveQuery | Promise>, + query: + | string + | LiveQuery + | Promise> + | (() => Promise>), params: unknown[] | undefined | null, key?: string, ): Omit, 'affectedRows'> | undefined { @@ -27,7 +31,11 @@ function useLiveQueryImpl( const liveQueryRef = useRef | undefined>() let liveQuery: LiveQuery | undefined let liveQueryChanged = false - if (!(typeof query === 'string') && !(query instanceof Promise)) { + if ( + !(typeof query === 'string') && + !(typeof query === 'function') && + !(query instanceof Promise) + ) { liveQuery = query liveQueryChanged = liveQueryRef.current !== liveQuery liveQueryRef.current = liveQuery @@ -49,6 +57,7 @@ function useLiveQueryImpl( if (cancelled) return setResults(results) } + if (typeof query === 'string') { const ret = key !== undefined @@ -66,6 +75,30 @@ function useLiveQueryImpl( setResults(liveQuery.initialResults) liveQuery.subscribe(cb) }) + + return () => { + cancelled = true + liveQueryRef.current?.unsubscribe(cb) + } + } else if (typeof query === 'function') { + query().then((liveQueryOrString) => { + if (cancelled) return + const liveQuery = + typeof liveQueryOrString === 'string' + ? key !== undefined + ? db.live.incrementalQuery( + liveQueryOrString, + currentParams, + key, + cb, + ) + : db.live.query(liveQueryOrString, currentParams, cb) + : liveQueryOrString + liveQueryRef.current = liveQuery + setResults(liveQuery.initialResults) + liveQuery.subscribe(cb) + }) + return () => { cancelled = true liveQueryRef.current?.unsubscribe(cb) @@ -73,6 +106,7 @@ function useLiveQueryImpl( } else if (liveQuery) { setResults(liveQuery.initialResults) liveQuery.subscribe(cb) + return () => { cancelled = true liveQuery.unsubscribe(cb) @@ -112,7 +146,15 @@ export function useLiveQuery( ): LiveQueryResults | undefined export function useLiveQuery( - query: string | LiveQuery | Promise>, + liveQueryPromise: () => Promise>, +): LiveQueryResults | undefined + +export function useLiveQuery( + query: + | string + | LiveQuery + | Promise> + | (() => Promise>), params?: unknown[] | null, ): LiveQueryResults | undefined { return useLiveQueryImpl(query, params)