From 1f0decaa938b5cdf621da84804fdda193aed6bac Mon Sep 17 00:00:00 2001 From: Pierre Leroux Date: Wed, 25 Oct 2023 14:03:58 +0200 Subject: [PATCH] fix(react): improve useApi hook (not used currently in codebase) --- src/renderer/common/hooks/useApi.ts | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/renderer/common/hooks/useApi.ts b/src/renderer/common/hooks/useApi.ts index 6b8d9cd32..307cefae1 100644 --- a/src/renderer/common/hooks/useApi.ts +++ b/src/renderer/common/hooks/useApi.ts @@ -16,21 +16,24 @@ import { ApiResponse } from "readium-desktop/common/redux/states/api"; import { TReturnPromiseOrGeneratorType } from "readium-desktop/typings/api"; import { useSyncExternalStore } from "./useSyncExternalStore"; -export function useApi(_requestId: string, apiPath: T, ...requestData: Parameters): ApiResponse> { +export function useApi(_requestId: string | undefined, apiPath: T): + [ApiResponse>, (...requestData: Parameters) => void] +{ const requestId = _requestId || React.useMemo(() => uuidv4(), []); const { store } = React.useContext(ReactReduxContext); React.useEffect(() => { + return () => { + store.dispatch(apiActions.clean.build(requestId)); + }; + }, []); + const apiAction = (...requestData: Parameters) => { const splitPath = apiPath.split("/"); const moduleId = splitPath[0] as TModuleApi; const methodId = splitPath[1] as TMethodApi; store.dispatch(apiActions.request.build(requestId, moduleId, methodId, requestData)); - - return () => { - store.dispatch(apiActions.clean.build(requestId)); - }; - }, []); // componentDidMount + }; const apiResult = useSyncExternalStore(store.subscribe, () => store.getState().api[requestId]); - return apiResult; + return [apiResult, apiAction]; };