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

use-pull-to-refresh.ts

40 lines1.5 KB

1import { RegistryContext } from "@effect/atom-react";
2import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
3import { type AsyncResult, type Atom } from "effect/reactivity";
4import { use, useCallback, useEffect, useRef, useState } from "react";
5​
6export function usePullToRefresh<A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E>> | null) {
7 const registry = use(RegistryContext);
8 const request = useRef<{ atom: NonNullable<typeof atom>; controller: AbortController } | null>(
9 null,
10 );
11 const [refreshingAtom, setRefreshingAtom] = useState<typeof atom>(null);
12 if (refreshingAtom !== null && refreshingAtom !== atom) setRefreshingAtom(null);
13 useEffect(
14 () => () => {
15 if (request.current?.atom === atom) request.current.controller.abort();
16 },
17 [atom],
18 );
19​
20 const onRefresh = useCallback(() => {
21 if (!atom || (request.current?.atom === atom && !request.current.controller.signal.aborted))
22 return;
23 request.current?.controller.abort();
24 const controller = new AbortController();
25 request.current = { atom, controller };
26 setRefreshingAtom(atom);
27 void executeAtomQuery(registry, atom, {
28 refresh: true,
29 signal: controller.signal,
30 reportFailure: false,
31 reportDefect: false,
32 }).finally(() => {
33 if (controller.signal.aborted || request.current?.controller !== controller) return;
34 request.current = null;
35 setRefreshingAtom(null);
36 });
37 }, [atom, registry]);
38​
39 return { refreshing: atom !== null && refreshingAtom === atom, onRefresh };