UNPKG

@tanstack/react-db

Version:

React integration for @tanstack/db

34 lines (33 loc) • 1.42 kB
import { useRef, useEffect } from "react"; import { prepareLiveQueryValue, createEffect } from "@tanstack/db"; import { useOptionalDbClient } from "./DbProvider.js"; import { getPreparedSources } from "./source-id-bindings.js"; function useLiveQueryEffect(config, deps = []) { const client = useOptionalDbClient(); const configRef = useRef(config); configRef.current = config; useEffect(() => { const query = prepareLiveQueryValue(config.query, client); if (!client) getPreparedSources(query, client, `useLiveQueryEffect`); const effect = createEffect({ id: config.id, query, skipInitial: config.skipInitial, onEnter: (event, ctx) => configRef.current.onEnter?.(event, ctx), onUpdate: (event, ctx) => configRef.current.onUpdate?.(event, ctx), onExit: (event, ctx) => configRef.current.onExit?.(event, ctx), onBatch: (events, ctx) => configRef.current.onBatch?.(events, ctx), onError: config.onError ? (error, event) => configRef.current.onError?.(error, event) : void 0, onSourceError: config.onSourceError ? (error) => configRef.current.onSourceError?.(error) : void 0 }); return () => { void effect.dispose().catch((error) => { console.error(`[useLiveQueryEffect] failed to dispose effect:`, error); }); }; }, [...deps, client]); } export { useLiveQueryEffect }; //# sourceMappingURL=useLiveQueryEffect.js.map