From 58067cbeb5a307fcde35d149e45cac5e3b76e08a Mon Sep 17 00:00:00 2001 From: Brent Traut Date: Fri, 22 Oct 2021 09:04:11 -0700 Subject: [PATCH 1/2] Memoize options generation --- src/index.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/index.ts b/src/index.ts index 05c52c9..c02caa8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,6 +4,7 @@ import { useCallback, useEffect, useLayoutEffect, + useMemo, useRef, useState, } from 'react'; @@ -238,9 +239,12 @@ const useAsyncInternal = ( const normalizedOptions = normalizeOptions(options); + // Use memoization to produce a stable options object post-normalization. + const memoizedOptions = useMemo(normalizedOptions, Object.values(normalizedOptions)); + const [currentParams, setCurrentParams] = useState(null); - const AsyncState = useAsyncState(normalizedOptions); + const AsyncState = useAsyncState(memoizedOptions); const isMounted = useIsMounted(); const CurrentPromise = useCurrentPromise(); @@ -263,7 +267,7 @@ const useAsyncInternal = ( if (shouldHandlePromise(promise)) { AsyncState.setResult(result); } - normalizedOptions.onSuccess(result, { + memoizedOptions.onSuccess(result, { isCurrent: () => CurrentPromise.is(promise), }); }, @@ -271,7 +275,7 @@ const useAsyncInternal = ( if (shouldHandlePromise(promise)) { AsyncState.setError(error); } - normalizedOptions.onError(error, { + memoizedOptions.onError(error, { isCurrent: () => CurrentPromise.is(promise), }); } @@ -291,8 +295,8 @@ const useAsyncInternal = ( const isMounting = !isMounted(); useEffect(() => { const execute = () => getLatestExecuteAsyncOperation()(...params); - isMounting && normalizedOptions.executeOnMount && execute(); - !isMounting && normalizedOptions.executeOnUpdate && execute(); + isMounting && memoizedOptions.executeOnMount && execute(); + !isMounting && memoizedOptions.executeOnUpdate && execute(); }, params); return { From 7cedd1936e60908cb063e1c494804ca469ccec4a Mon Sep 17 00:00:00 2001 From: Brent Traut Date: Fri, 22 Oct 2021 09:21:13 -0700 Subject: [PATCH 2/2] Fixed useMemo bug --- src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index c02caa8..37774b9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -240,7 +240,7 @@ const useAsyncInternal = ( const normalizedOptions = normalizeOptions(options); // Use memoization to produce a stable options object post-normalization. - const memoizedOptions = useMemo(normalizedOptions, Object.values(normalizedOptions)); + const memoizedOptions = useMemo(() => normalizedOptions, Object.values(normalizedOptions)); const [currentParams, setCurrentParams] = useState(null);