Open History to see the last commit
1import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
2import * as Cause from "effect/Cause";
3import * as Option from "effect/Option";
4import { AsyncResult, Atom } from "effect/unstable/reactivity";
5
6const EMPTY_ASYNC_RESULT_ATOM = Atom.make(AsyncResult.initial<never, never>(false)).pipe(
7 Atom.withLabel("web-environment-query:empty"),
8);
9
10export interface EnvironmentQueryView<A> {
11 readonly data: A | null;
12 readonly dataUpdatedAt: number;
13 readonly error: string | null;
14 readonly isPending: boolean;
15 readonly isSuccess: boolean;
16 readonly refresh: () => void;
17}
18
19export function formatEnvironmentQueryError(cause: Cause.Cause<unknown>): string {
20 const error = Cause.squash(cause);
21 return error instanceof Error && error.message.trim().length > 0
22 ? error.message
23 : "The environment request failed.";
24}
25
26export function useEnvironmentQuery<A, E>(
27 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>> | null,
28): EnvironmentQueryView<A> {
29 const selectedAtom = atom ?? EMPTY_ASYNC_RESULT_ATOM;
30 const result = useAtomValue(selectedAtom);
31 const refresh = useAtomRefresh(selectedAtom);
32 return {
33 data: Option.getOrNull(AsyncResult.value(result)),
34 dataUpdatedAt:
35 result._tag === "Success"
36 ? result.timestamp
37 : result._tag === "Failure"
38 ? (Option.getOrNull(result.previousSuccess)?.timestamp ?? 0)
39 : 0,
40 error: result._tag === "Failure" ? formatEnvironmentQueryError(result.cause) : null,
41 isPending: atom !== null && result.waiting,
42 isSuccess: result._tag === "Success",
43 refresh,
44 };
45}