Skip to content

Commit

Permalink
Refactor: memoize useTxHistory
Browse files Browse the repository at this point in the history
  • Loading branch information
katspaugh committed Nov 28, 2023
1 parent ffbaa7b commit 6bddd56
Showing 1 changed file with 22 additions and 17 deletions.
39 changes: 22 additions & 17 deletions src/hooks/useTxHistory.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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<TransactionListPage>(
() => {
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

0 comments on commit 6bddd56

Please sign in to comment.