1
0
forked from Kieran/snort
snort/packages/system-react/src/useRequestBuilder.tsx

42 lines
1.2 KiB
TypeScript
Raw Normal View History

2023-08-24 14:25:54 +00:00
import { useContext, useSyncExternalStore } from "react";
import { RequestBuilder, EmptySnapshot, NoteStore, StoreSnapshot } from "@snort/system";
2023-06-16 19:31:33 +00:00
import { unwrap } from "@snort/shared";
2023-08-24 14:25:54 +00:00
import { SnortContext } from "./context";
2023-03-28 14:34:01 +00:00
2023-06-16 19:31:33 +00:00
/**
* Send a query to the relays and wait for data
*/
2023-03-28 14:34:01 +00:00
const useRequestBuilder = <TStore extends NoteStore, TSnapshot = ReturnType<TStore["getSnapshotData"]>>(
2023-08-24 15:55:36 +00:00
type: { new (): TStore },
2023-07-24 14:30:21 +00:00
rb: RequestBuilder | null,
2023-03-28 14:34:01 +00:00
) => {
2023-08-24 14:25:54 +00:00
const system = useContext(SnortContext);
2023-03-28 14:34:01 +00:00
const subscribe = (onChanged: () => void) => {
2023-06-08 04:39:10 +00:00
if (rb) {
2023-06-16 19:31:33 +00:00
const q = system.Query<TStore>(type, rb);
2023-06-08 04:39:10 +00:00
const release = q.feed.hook(onChanged);
2023-06-08 05:27:27 +00:00
q.uncancel();
2023-06-08 04:39:10 +00:00
return () => {
q.cancel();
release();
};
}
2023-03-28 14:34:01 +00:00
return () => {
2023-06-08 04:39:10 +00:00
// noop
2023-03-28 14:34:01 +00:00
};
};
const getState = (): StoreSnapshot<TSnapshot> => {
2023-06-16 19:31:33 +00:00
const q = system.GetQuery(rb?.id ?? "");
2023-06-08 04:39:10 +00:00
if (q) {
return unwrap(q).feed?.snapshot as StoreSnapshot<TSnapshot>;
2023-03-28 14:34:01 +00:00
}
2023-03-28 15:41:57 +00:00
return EmptySnapshot as StoreSnapshot<TSnapshot>;
2023-03-28 14:34:01 +00:00
};
return useSyncExternalStore<StoreSnapshot<TSnapshot>>(
v => subscribe(v),
2023-07-24 14:30:21 +00:00
() => getState(),
2023-03-28 14:34:01 +00:00
);
};
2023-07-22 18:37:46 +00:00
export { useRequestBuilder };