From d7fccd5b008ea3cd0bf6e547ea4b0d9d271c1613 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fl=C3=A1vio=20Caetano?= Date: Tue, 26 Nov 2019 17:11:12 -0300 Subject: [PATCH] fix(useWorker): prevent multiple renders triggered by update This fixes an issue where updating `isLoading` and `error` would trigger multiple render since those were two different states. fix #16 --- src/index.tsx | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/index.tsx b/src/index.tsx index 79e4303..fce858c 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -99,21 +99,30 @@ export const useWorker = ( error: Error | undefined; callback: (...args: TArgs) => Promise; } => { - const [isLoading, setIsLoading] = useState(false); - const [error, setError] = useState(undefined); + const [{ isLoading, error }, setState] = useState({ + isLoading: false, + error: undefined as Error | undefined, + }); + + const setError = useCallback((error: Error | undefined) => { + setState(s => ({ ...s, error })); + }, []); + + const setIsLoading = useCallback((isLoading: boolean) => { + setState(s => ({ ...s, isLoading })); + }, []); + const callback = useCallback(async (...args: TArgs): Promise< TRet | undefined > => { try { setIsLoading(true); const result = await worker(...args); - setIsLoading(false); - setError(undefined); + setState({ isLoading: false, error: undefined }); return result; - } catch (e) { - setIsLoading(false); - setError(e); + } catch (error) { + setState({ isLoading: false, error }); } }, dependencies);