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

87 lines
2.5 KiB
TypeScript
Raw Normal View History

2021-07-14 20:21:40 +02:00
/*
This file is part of TALER
(C) 2016 GNUnet e.V.
TALER is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation; either version 3, or (at your option) any later version.
TALER is distributed in the hope that it will be useful, but WITHOUT ANY
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
TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
import {
NotificationType, TalerErrorDetail
} from "@gnu-taler/taler-util";
import { TalerError } from "@gnu-taler/taler-wallet-core";
import { useEffect, useMemo, useState } from "preact/hooks";
2022-03-29 04:41:07 +02:00
import * as wxApi from "../wxApi.js";
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;
}
2021-10-11 20:59:55 +02:00
export type HookResponse<T> = HookOk<T> | HookError | undefined;
2021-07-14 20:21:40 +02:00
export function useAsyncAsHook<T>(
fn: () => Promise<T | false>,
updateOnNotification?: Array<NotificationType>,
deps?: any[],
): HookResponse<T> {
const args = useMemo(() => ({
fn, updateOnNotification
// eslint-disable-next-line react-hooks/exhaustive-deps
}), deps || [])
2021-10-11 20:59:55 +02:00
const [result, setHookResponse] = useState<HookResponse<T>>(undefined);
2021-07-14 20:21:40 +02:00
useEffect(() => {
async function doAsync(): Promise<void> {
2021-07-14 20:21:40 +02:00
try {
const response = await args.fn();
if (response === false) return;
2021-10-11 20:59:55 +02:00
setHookResponse({ hasError: false, response });
2021-07-14 20:21:40 +02:00
} 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,
});
2021-10-11 20:59:55 +02:00
}
2021-07-14 20:21:40 +02:00
}
}
2021-11-15 15:18:58 +01:00
doAsync();
if (args.updateOnNotification && args.updateOnNotification.length > 0) {
return wxApi.onUpdateNotification(args.updateOnNotification, () => {
doAsync();
});
}
}, [args]);
2021-10-11 20:59:55 +02:00
return result;
2021-07-14 20:21:40 +02:00
}