aboutsummaryrefslogtreecommitdiff
path: root/packages/taler-wallet-webextension/src/hooks/useAsyncAsHook.ts
diff options
context:
space:
mode:
Diffstat (limited to 'packages/taler-wallet-webextension/src/hooks/useAsyncAsHook.ts')
-rw-r--r--packages/taler-wallet-webextension/src/hooks/useAsyncAsHook.ts47
1 files changed, 47 insertions, 0 deletions
diff --git a/packages/taler-wallet-webextension/src/hooks/useAsyncAsHook.ts b/packages/taler-wallet-webextension/src/hooks/useAsyncAsHook.ts
index e592073dd..d03455ff7 100644
--- a/packages/taler-wallet-webextension/src/hooks/useAsyncAsHook.ts
+++ b/packages/taler-wallet-webextension/src/hooks/useAsyncAsHook.ts
@@ -39,7 +39,12 @@ export interface HookOperationalError {
details: TalerErrorDetail;
}
+interface WithRetry {
+ retry: () => void;
+}
+
export type HookResponse<T> = HookOk<T> | HookError | undefined;
+export type HookResponseWithRetry<T> = ((HookOk<T> | HookError) & WithRetry) | undefined;
export function useAsyncAsHook<T>(
fn: () => Promise<T | false>,
@@ -84,3 +89,45 @@ export function useAsyncAsHook<T>(
}, [args]);
return result;
}
+
+export function useAsyncAsHook2<T>(
+ fn: () => Promise<T | false>,
+ deps?: any[],
+): HookResponseWithRetry<T> {
+
+ const [result, setHookResponse] = useState<HookResponse<T>>(undefined);
+
+ const args = useMemo(() => ({
+ fn
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }), deps || [])
+
+ async function doAsync(): Promise<void> {
+ try {
+ const response = await args.fn();
+ if (response === false) return;
+ setHookResponse({ hasError: false, response });
+ } catch (e) {
+ if (e instanceof TalerError) {
+ setHookResponse({
+ hasError: true,
+ operational: true,
+ details: e.errorDetail,
+ });
+ } else if (e instanceof Error) {
+ setHookResponse({
+ hasError: true,
+ operational: false,
+ message: e.message,
+ });
+ }
+ }
+ }
+
+ useEffect(() => {
+ doAsync();
+ }, [args]);
+
+ if (!result) return undefined;
+ return { ...result, retry: doAsync };
+}