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

query.ts

36 lines1.2 KB

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 error: string | null;
13 readonly isPending: boolean;
14 readonly refresh: () => void;
16​
17function formatError(cause: Cause.Cause<unknown>): string {
18 const error = Cause.squash(cause);
19 return error instanceof Error && error.message.trim().length > 0
20 ? error.message
21 : "The environment request failed.";
23​
24export function useEnvironmentQuery<A, E>(
25 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>> | null,
26): EnvironmentQueryView<A> {
27 const selectedAtom = atom ?? EMPTY_ASYNC_RESULT_ATOM;
28 const result = useAtomValue(selectedAtom);
29 const refresh = useAtomRefresh(selectedAtom);
30 return {
31 data: Option.getOrNull(AsyncResult.value(result)),
32 error: result._tag === "Failure" ? formatError(result.cause) : null,
33 isPending: atom !== null && result.waiting,
34 refresh,
35 };