From 168a6448723fa746f4890a28233ac3905d5ef62d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A1bio=20Santos?= Date: Tue, 9 Jun 2020 02:14:57 +0100 Subject: [PATCH] Stabilize result object This makes it possible to use the return value from the hooks in this library as dependencies for other hooks. --- src/index.ts | 53 +++++++++++++++++++++++++++++++++++----------------- 1 file changed, 36 insertions(+), 17 deletions(-) diff --git a/src/index.ts b/src/index.ts index 7f813fd..10708d5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,6 +4,7 @@ import { useLayoutEffect, useRef, useState, + useMemo, } from 'react'; // See https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85 @@ -287,15 +288,28 @@ const useAsyncInternal = ( } }, params); - return { - ...AsyncState.value, - set: AsyncState.set, - merge: AsyncState.merge, - reset: AsyncState.reset, - execute: executeAsyncOperation, - currentPromise: CurrentPromise.get(), - currentParams, - }; + const currentPromise = CurrentPromise.get(); + + return useMemo( + () => ({ + ...AsyncState.value, + set: AsyncState.set, + merge: AsyncState.merge, + reset: AsyncState.reset, + execute: executeAsyncOperation, + currentPromise, + currentParams, + }), + [ + AsyncState.value, + AsyncState.set, + AsyncState.merge, + AsyncState.reset, + executeAsyncOperation, + currentPromise, + currentParams, + ] + ); }; // override to allow passing an async function with no args: @@ -465,12 +479,17 @@ export const useAsyncFetchMore = ({ } }, [shouldReset]); - return { - canFetchMore: - value.status === 'success' && fetchMoreAsync.status !== 'loading', - loading: fetchMoreAsync.loading, - status: fetchMoreAsync.status, - fetchMore: fetchMoreAsync.execute, - isEnd, - }; + const canFetchMore = + value.status === 'success' && fetchMoreAsync.status !== 'loading'; + + return useMemo( + () => ({ + canFetchMore, + loading: fetchMoreAsync.loading, + status: fetchMoreAsync.status, + fetchMore: fetchMoreAsync.execute, + isEnd, + }), + [canFetchMore, fetchMoreAsync, isEnd] + ); };