38 lines
1.2 KiB
TypeScript
38 lines
1.2 KiB
TypeScript
import { useAtomValue } from "@effect/atom-react";
|
|
import * as Cause from "effect/Cause";
|
|
import * as Effect from "effect/Effect";
|
|
import * as Option from "effect/Option";
|
|
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
|
import { useCallback } from "react";
|
|
|
|
import { appAtomRegistry } from "../../rpc/atomRegistry";
|
|
import { fetchSessionState } from "./auth";
|
|
|
|
const primarySessionStateAtom = Atom.make(Effect.promise(fetchSessionState)).pipe(
|
|
Atom.swr({ staleTime: 5_000, revalidateOnMount: true }),
|
|
Atom.setIdleTTL(5 * 60_000),
|
|
Atom.withLabel("primary-environment:session"),
|
|
);
|
|
|
|
export function refreshPrimarySessionState(): void {
|
|
appAtomRegistry.refresh(primarySessionStateAtom);
|
|
}
|
|
|
|
export function usePrimarySessionState() {
|
|
const result = useAtomValue(primarySessionStateAtom);
|
|
const refresh = useCallback(() => {
|
|
refreshPrimarySessionState();
|
|
}, []);
|
|
let error: string | null = null;
|
|
if (result._tag === "Failure") {
|
|
const cause = Cause.squash(result.cause);
|
|
error = cause instanceof Error ? cause.message : "Could not read environment session.";
|
|
}
|
|
return {
|
|
data: Option.getOrNull(AsyncResult.value(result)),
|
|
error,
|
|
isPending: result.waiting,
|
|
refresh,
|
|
};
|
|
}
|