From 6bddd563612c194905626e099ef7df8a174abfbf Mon Sep 17 00:00:00 2001 From: katspaugh Date: Tue, 28 Nov 2023 18:19:45 +0100 Subject: [PATCH] Refactor: memoize useTxHistory --- src/hooks/useTxHistory.ts | 39 ++++++++++++++++++++++----------------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/src/hooks/useTxHistory.ts b/src/hooks/useTxHistory.ts index a41713600f..977b08edae 100644 --- a/src/hooks/useTxHistory.ts +++ b/src/hooks/useTxHistory.ts @@ -1,3 +1,5 @@ +import isEqual from 'lodash/isEqual' +import { useMemo } from 'react' import { getTransactionHistory, type TransactionListPage } from '@safe-global/safe-gateway-typescript-sdk' import { useAppSelector } from '@/store' import useAsync from './useAsync' @@ -12,39 +14,42 @@ const useTxHistory = ( error?: string loading: boolean } => { + // The latest page of the history is always in the store + const historyState = useAppSelector(selectTxHistory, isEqual) const [filter] = useTxFilter() - const { safe, safeAddress, safeLoaded } = useSafeInfo() - const { chainId } = safe + const { + safe: { chainId }, + safeAddress, + } = useSafeInfo() // If filter exists or pageUrl is passed, load a new history page from the API const [page, error, loading] = useAsync( () => { - if (!safeLoaded || !(filter || pageUrl)) return + if (!(filter || pageUrl)) return return filter ? fetchFilteredTxHistory(chainId, safeAddress, filter, pageUrl) : getTransactionHistory(chainId, safeAddress, pageUrl) }, - [chainId, safeAddress, safeLoaded, pageUrl, filter], + [chainId, safeAddress, pageUrl, filter], false, ) - // The latest page of the history is always in the store - const historyState = useAppSelector(selectTxHistory) + const isFetched = filter || pageUrl + const dataPage = isFetched ? page : historyState.data + const errorMessage = isFetched ? error?.message : historyState.error + const isLoading = isFetched ? loading : historyState.loading // Return the new page or the stored page - return filter || pageUrl - ? { - page, - error: error?.message, - loading: loading, - } - : { - page: historyState.data, - error: historyState.error, - loading: historyState.loading, - } + return useMemo( + () => ({ + page: dataPage, + error: errorMessage, + loading: isLoading, + }), + [dataPage, errorMessage, isLoading], + ) } export default useTxHistory