MCPcopy Create free account
hub / github.com/msgbyte/tailchat / useAsyncFn

Function useAsyncFn

client/shared/hooks/useAsyncFn.ts:36–69  ·  view source on GitHub ↗
(
  fn: T,
  deps: DependencyList = [],
  initialState: StateFromFunctionReturningPromise<T> = { loading: false }
)

Source from the content-addressed store, hash-verified

34> = [StateFromFunctionReturningPromise<T>, T];
35
36export function useAsyncFn<T extends FunctionReturningPromise>(
37 fn: T,
38 deps: DependencyList = [],
39 initialState: StateFromFunctionReturningPromise<T> = { loading: false }
40): AsyncFnReturn<T> {
41 const lastCallId = useRef(0);
42 const isMounted = useMountedState();
43 const [state, set] =
44 useState<StateFromFunctionReturningPromise<T>>(initialState);
45
46 const callback = useCallback((...args: Parameters<T>): ReturnType<T> => {
47 const callId = ++lastCallId.current;
48 set((prevState) => ({ ...prevState, loading: true }));
49
50 return fn(...args).then(
51 (value) => {
52 isMounted() &&
53 callId === lastCallId.current &&
54 set({ value, loading: false });
55
56 return value;
57 },
58 (error) => {
59 isMounted() &&
60 callId === lastCallId.current &&
61 set({ error, loading: false });
62
63 return error;
64 }
65 ) as ReturnType<T>;
66 }, deps);
67
68 return [state, callback as unknown as T];
69}

Callers 15

useAsyncFunction · 0.90
useAsyncRequestFunction · 0.90
useAsyncRefreshFunction · 0.90
useAvailableServicesFunction · 0.90
AddFriend.tsxFile · 0.85
RequestSend.tsxFile · 0.85
RegisterView.tsxFile · 0.85
LoginView.tsxFile · 0.85
DrawModal.tsxFile · 0.85

Calls 3

useMountedStateFunction · 0.90
setFunction · 0.85
fnFunction · 0.50

Tested by

no test coverage detected