From f0240018d64de0ce8c1388f2742a013fde6ba5ea Mon Sep 17 00:00:00 2001 From: Enrico Ros Date: Sat, 3 Aug 2024 23:27:33 -0700 Subject: [PATCH] useAsyncCall: improvements --- src/common/util/hooks/useAsyncCall.ts | 41 +++++++++++++-------------- 1 file changed, 19 insertions(+), 22 deletions(-) diff --git a/src/common/util/hooks/useAsyncCall.ts b/src/common/util/hooks/useAsyncCall.ts index c29ba3f97..166c56157 100644 --- a/src/common/util/hooks/useAsyncCall.ts +++ b/src/common/util/hooks/useAsyncCall.ts @@ -45,30 +45,27 @@ export function useAsyncCall(asyncFunction: AsyncF }; }, [asyncFunction]); - const execute = React.useCallback( - async (...args: TArgs): Promise => { - setState(prev => ({ ...prev, isLoading: true, error: null })); + const execute = React.useCallback(async (...args: TArgs): Promise => { + setState(prev => ({ ...prev, isLoading: true, error: null })); - try { - const result = await latestAsyncFunction.current(...args); - if (isMounted.current) { - setState({ isLoading: false, error: null, data: result }); - } - return result; - } catch (err) { - const error = err instanceof Error ? err : new Error('An error occurred'); - if (isMounted.current) { - setState(prev => ({ - ...prev, - isLoading: false, - error, - })); - } - throw error; + try { + const result = await latestAsyncFunction.current(...args); + if (isMounted.current) { + setState({ isLoading: false, error: null, data: result }); } - }, - [], - ); + return result; + } catch (err) { + const error = err instanceof Error ? err : new Error('An error occurred'); + if (isMounted.current) { + setState(prev => ({ + ...prev, + isLoading: false, + error, + })); + } + throw error; + } + }, []); return [state.isLoading, execute, state.error, state.data]; } \ No newline at end of file