Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import {
3 createManagedRelayQueryManager,
4 managedRelaySessionAtom,
5 readManagedRelaySnapshotState,
6} from "@t3tools/client-runtime/relay";
7import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
8import { AsyncResult, Atom } from "effect/unstable/reactivity";
9import { useCallback, useEffect } from "react";
10
11import { runtimeContextLayer } from "../../lib/runtime";
12import { appAtomRegistry } from "../../state/atom-registry";
13import { cloudDebugLog } from "./cloudDebugLog";
14
15const managedRelayAtomRuntime = Atom.runtime(runtimeContextLayer);
16
17export const managedRelayQueryManager = createManagedRelayQueryManager(managedRelayAtomRuntime, {
18 onQueryEvent: (event) =>
19 cloudDebugLog(`query:${event.operation}:${event.stage}:${event.phase}`, { ...event }),
20});
21
22const EMPTY_ENVIRONMENTS_ATOM = Atom.make(
23 AsyncResult.success<ReadonlyArray<RelayClientEnvironmentRecord>>([]),
24).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:mobile:environments:null"));
25
26export function useManagedRelayEnvironments() {
27 const session = useAtomValue(managedRelaySessionAtom);
28 const accountId = session?.accountId ?? null;
29 const atom = accountId
30 ? managedRelayQueryManager.environmentsAtom(accountId)
31 : EMPTY_ENVIRONMENTS_ATOM;
32 const result = useAtomValue(atom);
33 const snapshot = readManagedRelaySnapshotState(result);
34 useEffect(() => {
35 if (snapshot.error) {
36 console.error("[t3-cloud] Relay environment listing failed", {
37 message: snapshot.error,
38 traceId: snapshot.errorTraceId,
39 });
40 }
41 }, [snapshot.error, snapshot.errorTraceId]);
42 const refresh = useCallback(() => {
43 if (accountId) {
44 managedRelayQueryManager.refreshEnvironments(appAtomRegistry, accountId);
45 }
46 }, [accountId]);
47
48 return {
49 ...snapshot,
50 accountId,
51 refresh,
52 };
53}
54
55export function refreshManagedRelayEnvironments(): void {
56 const session = appAtomRegistry.get(managedRelaySessionAtom);
57 if (session) {
58 managedRelayQueryManager.refreshEnvironments(appAtomRegistry, session.accountId);
59 }
60}