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

58 lines
1.7 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 } from "@gnu-taler/taler-util";
2021-07-14 20:21:40 +02:00
import { useEffect, useState } from "preact/hooks";
import * as wxApi from "../wxApi";
2021-10-11 20:59:55 +02:00
interface HookOk<T> {
hasError: false;
response: T;
2021-07-14 20:21:40 +02:00
}
2021-10-11 20:59:55 +02:00
interface HookError {
hasError: true;
message: string;
2021-07-14 20:21:40 +02:00
}
2021-10-11 20:59:55 +02:00
export type HookResponse<T> = HookOk<T> | HookError | undefined;
2021-07-14 20:21:40 +02:00
//"withdraw-group-finished"
export function useAsyncAsHook<T>(
fn: () => Promise<T>,
updateOnNotification?: Array<NotificationType>,
): HookResponse<T> {
2021-10-11 20:59:55 +02:00
const [result, setHookResponse] = useState<HookResponse<T>>(undefined);
2021-07-14 20:21:40 +02:00
useEffect(() => {
2021-10-11 20:59:55 +02:00
async function doAsync() {
2021-07-14 20:21:40 +02:00
try {
2021-10-11 20:59:55 +02:00
const response = await fn();
setHookResponse({ hasError: false, response });
2021-07-14 20:21:40 +02:00
} catch (e) {
2021-10-11 20:59:55 +02:00
if (e instanceof Error) {
setHookResponse({ hasError: true, message: e.message });
}
2021-07-14 20:21:40 +02:00
}
}
2021-11-15 15:18:58 +01:00
doAsync();
if (updateOnNotification && updateOnNotification.length > 0) {
return wxApi.onUpdateNotification(updateOnNotification, () => {
doAsync();
});
}
2021-07-14 20:21:40 +02:00
}, []);
2021-10-11 20:59:55 +02:00
return result;
2021-07-14 20:21:40 +02:00
}