Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

sessionState.ts

37 lines1.2 KB

1import { useAtomValue } from "@effect/atom-react";
2import * as Cause from "effect/Cause";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import { AsyncResult, Atom } from "effect/unstable/reactivity";
6import { useCallback } from "react";
7​
8import { appAtomRegistry } from "../../rpc/atomRegistry";
9import { fetchSessionState } from "./auth";
10​
11const primarySessionStateAtom = Atom.make(Effect.promise(fetchSessionState)).pipe(
12 Atom.swr({ staleTime: 5_000, revalidateOnMount: true }),
13 Atom.setIdleTTL(5 * 60_000),
14 Atom.withLabel("primary-environment:session"),
15);
16​
17function refreshPrimarySessionState(): void {
18 appAtomRegistry.refresh(primarySessionStateAtom);
20​
21export function usePrimarySessionState() {
22 const result = useAtomValue(primarySessionStateAtom);
23 const refresh = useCallback(() => {
24 refreshPrimarySessionState();
25 }, []);
26 let error: string | null = null;
27 if (result._tag === "Failure") {
28 const cause = Cause.squash(result.cause);
29 error = cause instanceof Error ? cause.message : "Could not read environment session.";
30 }
31 return {
32 data: Option.getOrNull(AsyncResult.value(result)),
33 error,
34 isPending: result.waiting,
35 refresh,
36 };