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/reactivity";
5
6const EMPTY_ASYNC_RESULT_ATOM = Atom.make(AsyncResult.initial<never, never>(false)).pipe(
7 Atom.withLabel("mobile-environment-query:empty"),
8);
9
10export interface EnvironmentQueryView<A> {
11 readonly data: A | null;
12 readonly successResult: AsyncResult.Success<A, unknown> | null;
13 readonly error: string | null;
14 readonly failure: unknown;
15 readonly isPending: boolean;
16 readonly isSuccess: boolean;
17 readonly refresh: () => void;
18}
19
20function formatError(cause: Cause.Cause<unknown>): string {
21 const error = Cause.squash(cause);
22 return error instanceof Error && error.message.trim().length > 0
23 ? error.message
24 : "The environment request failed.";
25}
26
27export function useEnvironmentQuery<A, E>(
28 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>> | null,
29): EnvironmentQueryView<A> {
30 const selectedAtom = atom ?? EMPTY_ASYNC_RESULT_ATOM;
31 const result = useAtomValue(selectedAtom);
32 const refresh = useAtomRefresh(selectedAtom);
33 return {
34 data: Option.getOrNull(AsyncResult.value(result)),
35 // Data may be structurally shared; only a settled success proves a new response.
36 successResult: result._tag === "Success" && !result.waiting ? result : null,
37 failure: result._tag === "Failure" ? Cause.squash(result.cause) : null,
38 error: result._tag === "Failure" ? formatError(result.cause) : null,
39 isPending: atom !== null && result.waiting,
40 isSuccess: result._tag === "Success",
41 refresh,
42 };
43}