Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 45 additions & 3 deletions packages/pglite-react/src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ function paramsEqual(
}

function useLiveQueryImpl<T = { [key: string]: unknown }>(
query: string | LiveQuery<T> | Promise<LiveQuery<T>>,
query:
| string
| LiveQuery<T>
| Promise<LiveQuery<T>>
| (() => Promise<string | LiveQuery<T>>),
params: unknown[] | undefined | null,
key?: string,
): Omit<LiveQueryResults<T>, 'affectedRows'> | undefined {
Expand All @@ -27,7 +31,11 @@ function useLiveQueryImpl<T = { [key: string]: unknown }>(
const liveQueryRef = useRef<LiveQuery<T> | undefined>()
let liveQuery: LiveQuery<T> | 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
Expand All @@ -49,6 +57,7 @@ function useLiveQueryImpl<T = { [key: string]: unknown }>(
if (cancelled) return
setResults(results)
}

if (typeof query === 'string') {
const ret =
key !== undefined
Expand All @@ -66,13 +75,38 @@ function useLiveQueryImpl<T = { [key: string]: unknown }>(
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<T>(
liveQueryOrString,
currentParams,
key,
cb,
)
: db.live.query<T>(liveQueryOrString, currentParams, cb)
: liveQueryOrString
liveQueryRef.current = liveQuery
setResults(liveQuery.initialResults)
liveQuery.subscribe(cb)
})

return () => {
cancelled = true
liveQueryRef.current?.unsubscribe(cb)
}
} else if (liveQuery) {
setResults(liveQuery.initialResults)
liveQuery.subscribe(cb)

return () => {
cancelled = true
liveQuery.unsubscribe(cb)
Expand Down Expand Up @@ -112,7 +146,15 @@ export function useLiveQuery<T = { [key: string]: unknown }>(
): LiveQueryResults<T> | undefined

export function useLiveQuery<T = { [key: string]: unknown }>(
query: string | LiveQuery<T> | Promise<LiveQuery<T>>,
liveQueryPromise: () => Promise<string | LiveQuery<T>>,
): LiveQueryResults<T> | undefined

export function useLiveQuery<T = { [key: string]: unknown }>(
query:
| string
| LiveQuery<T>
| Promise<LiveQuery<T>>
| (() => Promise<string | LiveQuery<T>>),
params?: unknown[] | null,
): LiveQueryResults<T> | undefined {
return useLiveQueryImpl<T>(query, params)
Expand Down
Loading