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

useLiveQueryEffect.ts

83 lines2.6 KB

1import { useEffect, useRef } from 'react'
2import { createEffect, prepareLiveQueryValue } from '@tanstack/db'
3import { useOptionalDbClient } from './DbProvider'
4import { resumeSyncStarts } from './source-id-bindings'
5import type {
6 DeferredLiveQueryCollections,
7 Effect,
8 EffectConfig,
9} from '@tanstack/db'
10​
11/**
12 * React hook for creating a reactive effect that fires handlers when rows
13 * enter, exit, or update within a query result.
14 *
15 * The effect is created on mount and disposed on unmount. If `deps` change,
16 * the previous effect is disposed and a new one is created.
17 *
18 * @example
19 * ```tsx
20 * function ChatComponent() {
21 * useLiveQueryEffect(
22 * {
23 * query: (q) => q.from({ msg: messages }).where(({ msg }) => eq(msg.role, 'user')),
24 * skipInitial: true,
25 * onEnter: async (event) => {
26 * await generateResponse(event.value)
27 * },
28 * },
29 * []
30 * )
31 *
32 * return <div>...</div>
33 * }
34 * ```
35 */
36export function useLiveQueryEffect<
37 TRow extends object = Record<string, unknown>,
38 TKey extends string | number = string | number,
39>(config: EffectConfig<TRow, TKey>, deps: React.DependencyList = []): void {
40 const client = useOptionalDbClient()
41 const configRef = useRef<EffectConfig<TRow, TKey>>(config)
42 configRef.current = config
43​
44 useEffect(() => {
45 const deferredCollections: DeferredLiveQueryCollections = new Set()
46 let effect: Effect | undefined
47 try {
48 const query = prepareLiveQueryValue(
49 config.query,
50 client,
51 deferredCollections,
52 ) as EffectConfig<TRow, TKey>[`query`]
53 effect = createEffect<TRow, TKey>({
54 id: config.id,
55 query,
56 skipInitial: config.skipInitial,
57 onEnter: (event, ctx) => configRef.current.onEnter?.(event, ctx),
58 onUpdate: (event, ctx) => configRef.current.onUpdate?.(event, ctx),
59 onExit: (event, ctx) => configRef.current.onExit?.(event, ctx),
60 onBatch: (events, ctx) => configRef.current.onBatch?.(events, ctx),
61 onError: config.onError
62 ? (error, event) => configRef.current.onError?.(error, event)
63 : undefined,
64 onSourceError: config.onSourceError
65 ? (error) => configRef.current.onSourceError?.(error)
66 : undefined,
67 })
68 resumeSyncStarts(deferredCollections)
69 } catch (error) {
70 try {
71 resumeSyncStarts(deferredCollections)
72 } finally {
73 void effect?.dispose()
74 }
75 throw error
76 }
77​
78 return () => {
79 // Fire-and-forget disposal; AbortSignal cancels in-flight work
80 void effect.dispose()
81 }
82 }, [...deps, client])