From 89435696f9a28316ab3dc5ef7c73776d092da89c Mon Sep 17 00:00:00 2001 From: Sebastian Date: Wed, 30 Mar 2022 14:36:24 -0300 Subject: useAsync use an optional deps for callback, most of the time it just need to be rendered once --- .../src/hooks/useAsyncAsHook.ts | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) (limited to 'packages/taler-wallet-webextension/src/hooks/useAsyncAsHook.ts') diff --git a/packages/taler-wallet-webextension/src/hooks/useAsyncAsHook.ts b/packages/taler-wallet-webextension/src/hooks/useAsyncAsHook.ts index 4e86c5ee5..b2d71874f 100644 --- a/packages/taler-wallet-webextension/src/hooks/useAsyncAsHook.ts +++ b/packages/taler-wallet-webextension/src/hooks/useAsyncAsHook.ts @@ -17,7 +17,7 @@ import { NotificationType, TalerErrorDetail } from "@gnu-taler/taler-util"; import { TalerError } from "@gnu-taler/taler-wallet-core"; -import { useEffect, useState } from "preact/hooks"; +import { useCallback, useEffect, useMemo, useState } from "preact/hooks"; import * as wxApi from "../wxApi.js"; interface HookOk { @@ -41,16 +41,22 @@ export interface HookOperationalError { export type HookResponse = HookOk | HookError | undefined; -//"withdraw-group-finished" export function useAsyncAsHook( fn: () => Promise, updateOnNotification?: Array, + deps?: any[], ): HookResponse { + + const args = useMemo(() => ({ + fn, updateOnNotification + // eslint-disable-next-line react-hooks/exhaustive-deps + }), deps || []) const [result, setHookResponse] = useState>(undefined); + useEffect(() => { async function doAsync(): Promise { try { - const response = await fn(); + const response = await args.fn(); setHookResponse({ hasError: false, response }); } catch (e) { if (e instanceof TalerError) { @@ -69,11 +75,11 @@ export function useAsyncAsHook( } } doAsync(); - if (updateOnNotification && updateOnNotification.length > 0) { - return wxApi.onUpdateNotification(updateOnNotification, () => { + if (args.updateOnNotification && args.updateOnNotification.length > 0) { + return wxApi.onUpdateNotification(args.updateOnNotification, () => { doAsync(); }); } - }, [fn, updateOnNotification]); + }, [args]); return result; } -- cgit v1.2.3