Open History to see the last commit
1import { useEffect, useRef } from 'react'
2import { createEffect } from '@tanstack/db'
3import type { Effect, EffectConfig } from '@tanstack/db'
4
5/**
6 * React hook for creating a reactive effect that fires handlers when rows
7 * enter, exit, or update within a query result.
8 *
9 * The effect is created on mount and disposed on unmount. If `deps` change,
10 * the previous effect is disposed and a new one is created.
11 *
12 * @example
13 * ```tsx
14 * function ChatComponent() {
15 * useLiveQueryEffect(
16 * {
17 * query: (q) => q.from({ msg: messages }).where(({ msg }) => eq(msg.role, 'user')),
18 * skipInitial: true,
19 * onEnter: async (event) => {
20 * await generateResponse(event.value)
21 * },
22 * },
23 * []
24 * )
25 *
26 * return <div>...</div>
27 * }
28 * ```
29 */
30export function useLiveQueryEffect<
31 TRow extends object = Record<string, unknown>,
32 TKey extends string | number = string | number,
33>(config: EffectConfig<TRow, TKey>, deps: React.DependencyList = []): void {
34 const configRef = useRef<EffectConfig<TRow, TKey>>(config)
35 configRef.current = config
36
37 useEffect(() => {
38 const effect: Effect = createEffect<TRow, TKey>({
39 id: config.id,
40 query: config.query,
41 skipInitial: config.skipInitial,
42 onEnter: (event, ctx) => configRef.current.onEnter?.(event, ctx),
43 onUpdate: (event, ctx) => configRef.current.onUpdate?.(event, ctx),
44 onExit: (event, ctx) => configRef.current.onExit?.(event, ctx),
45 onBatch: (events, ctx) => configRef.current.onBatch?.(events, ctx),
46 onError: config.onError
47 ? (error, event) => configRef.current.onError?.(error, event)
48 : undefined,
49 onSourceError: config.onSourceError
50 ? (error) => configRef.current.onSourceError?.(error)
51 : undefined,
52 })
53
54 return () => {
55 // Fire-and-forget disposal; AbortSignal cancels in-flight work
56 effect.dispose()
57 }
58 }, deps)
59}