wallet-core/packages/taler-wallet-webextension/src/hooks/useAsyncAsHook.ts

91 lines
2.4 KiB
TypeScript
Raw Normal View History

2021-07-14 20:21:40 +02:00
/*
2022-06-06 17:05:26 +02:00
This file is part of GNU Taler
(C) 2022 Taler Systems S.A.
2021-07-14 20:21:40 +02:00
2022-06-06 17:05:26 +02:00
GNU Taler is free software; you can redistribute it and/or modify it under the
2021-07-14 20:21:40 +02:00
terms of the GNU General Public License as published by the Free Software
Foundation; either version 3, or (at your option) any later version.
2022-06-06 17:05:26 +02:00
GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
2021-07-14 20:21:40 +02:00
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
2022-06-06 17:05:26 +02:00
GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
2021-07-14 20:21:40 +02:00
*/
2022-10-25 17:23:08 +02:00
import { TalerErrorDetail } from "@gnu-taler/taler-util";
import { TalerError } from "@gnu-taler/taler-wallet-core";
import { useEffect, useMemo, useState } from "preact/hooks";
2021-07-14 20:21:40 +02:00
export interface HookOk<T> {
2021-10-11 20:59:55 +02:00
hasError: false;
response: T;
2021-07-14 20:21:40 +02:00
}
export type HookError = HookGenericError | HookOperationalError;
export interface HookGenericError {
2021-10-11 20:59:55 +02:00
hasError: true;
operational: false;
2021-10-11 20:59:55 +02:00
message: string;
2021-07-14 20:21:40 +02:00
}
export interface HookOperationalError {
hasError: true;
operational: true;
details: TalerErrorDetail;
}
2022-04-21 19:23:53 +02:00
interface WithRetry {
retry: () => void;
}
2021-10-11 20:59:55 +02:00
export type HookResponse<T> = HookOk<T> | HookError | undefined;
2022-06-06 05:09:25 +02:00
export type HookResponseWithRetry<T> =
| ((HookOk<T> | HookError) & WithRetry)
| undefined;
2021-07-14 20:21:40 +02:00
export function useAsyncAsHook<T>(
2022-04-21 19:23:53 +02:00
fn: () => Promise<T | false>,
deps?: any[],
): HookResponseWithRetry<T> {
const [result, setHookResponse] = useState<HookResponse<T>>(undefined);
2022-06-06 05:09:25 +02:00
const args = useMemo(
() => ({
fn,
// eslint-disable-next-line react-hooks/exhaustive-deps
}),
deps || [],
);
2022-04-21 19:23:53 +02:00
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 };
}