Skip to content

Commit

Permalink
update useAsyncFn hook
Browse files Browse the repository at this point in the history
  • Loading branch information
edelgarat committed Jul 28, 2024
1 parent c2e14ff commit 88c2cfa
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 9 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@worksolutions/react-utils",
"private": false,
"version": "2.2.5",
"version": "2.2.6",
"description": "",
"types": "dist/esm/index.d.ts",
"main": "dist/cjs/index.js",
Expand Down
9 changes: 3 additions & 6 deletions src/hooks/useAsyncFn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,14 @@ export type AsyncState<T> =

type FunctionReturningPromise<VALUE> = (...args: any[]) => Promise<VALUE>;

const initialStateValue = { loading: false };
export function useAsyncFn<FUNC extends FunctionReturningPromise<any>>(
func: FUNC,
deps: DependencyList,
initialState: AsyncState<
FUNC extends FunctionReturningPromise<infer RESULT> ? RESULT : unknown
> = initialStateValue as any,
initialState?: AsyncState<FUNC extends FunctionReturningPromise<infer RESULT> ? RESULT : unknown>,
) {
const lastCallId = React.useRef(0);
const isMounted = useMountedState();
const [state, setState] = React.useState(initialState);
const [state, setState] = React.useState(initialState ?? { loading: false });
const stateRef = useSyncToRef(state);
const loadingAvailable = React.useRef(true);
const enableLoadingAvailable = useCallback(() => (loadingAvailable.current = true), []);
Expand All @@ -41,7 +38,7 @@ export function useAsyncFn<FUNC extends FunctionReturningPromise<any>>(
},
(error) => {
if (isMounted() && callId === lastCallId.current) setState({ error, loading: false });
return error;
throw error;
},
);
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand Down

0 comments on commit 88c2cfa

Please sign in to comment.