MCPcopy Index your code
hub / github.com/streamich/react-use / useAsyncFn

Function useAsyncFn

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

Source from the content-addressed store, hash-verified

34];
35
36export default 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] = useState<StateFromFunctionReturningPromise<T>>(initialState);
44
45 const callback = useCallback((...args: Parameters<T>): ReturnType<T> => {
46 const callId = ++lastCallId.current;
47
48 if (!state.loading) {
49 set((prevState) => ({ ...prevState, loading: true }));
50 }
51
52 return fn(...args).then(
53 (value) => {
54 isMounted() && callId === lastCallId.current && set({ value, loading: false });
55
56 return value;
57 },
58 (error) => {
59 isMounted() && callId === lastCallId.current && set({ error, loading: false });
60
61 return error;
62 }
63 ) as ReturnType<T>;
64 }, deps);
65
66 return [state, callback as unknown as T];
67}

Callers 3

DemoFunction · 0.90
useAsyncFunction · 0.85

Calls 3

useMountedStateFunction · 0.85
fnFunction · 0.85
setFunction · 0.70

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…