import { useSyncExternalStore } from "react"; import { RequestBuilder, System } from "System"; import { EmptySnapshot, NoteStore, StoreSnapshot } from "System/NoteCollection"; import { unwrap } from "Util"; const useRequestBuilder = >( type: { new (): TStore }, rb: RequestBuilder | null, debounced?: number ) => { const subscribe = (onChanged: () => void) => { const store = System.Query(type, rb); let t: ReturnType | undefined; const release = store.hook(() => { if (!t) { t = setTimeout(() => { clearTimeout(t); t = undefined; onChanged(); }, debounced ?? 500); } }); return () => { if (rb?.id) { System.CancelQuery(rb.id); } release(); }; }; const getState = (): StoreSnapshot => { if (rb?.id) { const q = System.GetQuery(rb.id); if (q) { return unwrap(q).feed?.snapshot as StoreSnapshot; } } return EmptySnapshot as StoreSnapshot; }; return useSyncExternalStore>( v => subscribe(v), () => getState() ); }; export default useRequestBuilder;