|
| 1 | +import { useEffect, useMemo } from 'react'; |
| 2 | +import { usePowerSync, useStatus, UseSyncStreamOptions } from '@powersync/react'; |
| 3 | + |
| 4 | +/** |
| 5 | + * Creates multiple PowerSync stream subscriptions. Subscriptions are kept alive as long as the |
| 6 | + * React component calling this function. When it unmounts, or when the streams array contents |
| 7 | + * change, all previous subscriptions are unsubscribed before new ones are created. |
| 8 | + */ |
| 9 | +export function useSyncStreams(streams: UseSyncStreamOptions[]) { |
| 10 | + const db = usePowerSync(); |
| 11 | + const status = useStatus(); |
| 12 | + |
| 13 | + // Serialize streams so the effect only re-runs when content actually changes. |
| 14 | + // We also parse it back so the effect closure uses the EXACT same streams that triggered it — |
| 15 | + // avoiding the stale-ref problem where streamsRef.current may have advanced to a newer render |
| 16 | + // by the time the effect flushes. |
| 17 | + const serialized = useMemo(() => JSON.stringify(streams), [streams]); |
| 18 | + const frozenStreams = useMemo<UseSyncStreamOptions[]>(() => JSON.parse(serialized), [serialized]); |
| 19 | + |
| 20 | + useEffect(() => { |
| 21 | + const abort = new AbortController(); |
| 22 | + |
| 23 | + const promises = frozenStreams.map((options) => |
| 24 | + db.syncStream(options.name, options.parameters ?? undefined).subscribe(options) |
| 25 | + ); |
| 26 | + |
| 27 | + Promise.all(promises).then((resolvedSubs) => { |
| 28 | + if (abort.signal.aborted) { |
| 29 | + // Cleanup already ran before all promises resolved — unsubscribe immediately. |
| 30 | + for (const sub of resolvedSubs) { |
| 31 | + sub.unsubscribe(); |
| 32 | + } |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + // Cleanup will run eventually — unsubscribe when it does. |
| 37 | + abort.signal.addEventListener('abort', () => { |
| 38 | + for (const sub of resolvedSubs) { |
| 39 | + sub.unsubscribe(); |
| 40 | + } |
| 41 | + }); |
| 42 | + }); |
| 43 | + |
| 44 | + return () => abort.abort(); |
| 45 | + }, [frozenStreams]); |
| 46 | + |
| 47 | + return useMemo( |
| 48 | + () => |
| 49 | + streams.map((options) => |
| 50 | + status.forStream({ name: options.name, parameters: options.parameters ?? null }) ?? null |
| 51 | + ), |
| 52 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 53 | + [status, serialized] |
| 54 | + ); |
| 55 | +} |
0 commit comments