Skip to content

Commit

Permalink
Add useAsyncMemo hook for memoizing async function results + use it…
Browse files Browse the repository at this point in the history
… in `useSignerAddress` hook
  • Loading branch information
tmjssz committed Aug 12, 2024
1 parent 073b4f1 commit 2980f2d
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 9 deletions.
1 change: 1 addition & 0 deletions src/SafeProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export const SafeContext = createContext<SafeContextType>({
publicClient: undefined,
signerClient: undefined
})

export type SafeProviderProps = {
config: SafeConfig
}
Expand Down
21 changes: 21 additions & 0 deletions src/hooks/helpers/useAsyncMemo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { DependencyList, useEffect, useState } from 'react'

/**
* Hook that memoizes the result of an async function.
* @param factory Async function of which the result should be memoized.
* @param deps Dependency list
* @returns Current result or `undefined` if not available.
*/
export function useAsyncMemo<T>(factory: () => Promise<T>, deps: DependencyList): T | undefined {
const [result, setResult] = useState<T | undefined>(undefined)

useEffect(() => {
factory().then((newResult) => {
if (newResult !== result) {
setResult(newResult)
}
})
}, [...deps, factory, result])

return result
}
15 changes: 6 additions & 9 deletions src/hooks/useSignerAddress.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useEffect, useState } from 'react'
import type { Address } from 'viem'
import { ConfigParam, SafeConfigWithSigner } from '@/types/index.js'
import { useSignerClient } from '@/hooks/useSignerClient.js'
import { useAsyncMemo } from '@/hooks/helpers/useAsyncMemo.js'

export type UseSignerAddressParams = ConfigParam<SafeConfigWithSigner>
export type UseSignerAddressReturnType = Address | undefined
Expand All @@ -14,15 +14,12 @@ export type UseSignerAddressReturnType = Address | undefined
*/
export function useSignerAddress(params: UseSignerAddressParams = {}): UseSignerAddressReturnType {
const signerClient = useSignerClient({ config: params.config })
const [signerAddress, setSignerAddress] = useState<UseSignerAddressReturnType>()

useEffect(() => {
if (signerClient) {
signerClient?.protocolKit.getSafeProvider().getSignerAddress().then(setSignerAddress)
} else {
setSignerAddress(undefined)
}
}, [signerClient])
const signerAddress = useAsyncMemo(
async () =>
signerClient ? signerClient.protocolKit.getSafeProvider().getSignerAddress() : undefined,
[signerClient]
)

return signerAddress
}

0 comments on commit 2980f2d

Please sign in to comment.