Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: useContractRead & useContractReads data instability #659

Merged
merged 4 commits into from
Jul 5, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/brown-carrots-fail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'wagmi': patch
---

Added an `isDataEqual` config option to `useContractRead`, `useContractReads` & `useContractInfiniteReads` to define whether or not that data has changed. Defaults to `deepEqual`.
5 changes: 5 additions & 0 deletions .changeset/smart-lemons-train.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'wagmi': patch
---

Fixed an issue where `useContractRead` & `useContractReads` would return unstable data.
29 changes: 29 additions & 0 deletions docs/pages/docs/hooks/useContractInfiniteReads.en-US.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,35 @@ function App() {
}
```

### isDataEqual (optional)

Determines if the data has changed or not. Defaults to `deepEqual`.

```tsx {20}
import { useContractInfiniteReads } from 'wagmi'

function App() {
const { data, isError, isLoading } = useContractInfiniteReads({
cacheKey: 'mlootAttributes',
contracts: (param = 0) => [
{
addressOrName: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df',
contractInterface: mlootABI,
functionName: 'getChest',
args: [param],
},
{
addressOrName: '0x1dfe7ca09e99d10835bf73044a23b73fc20623df',
contractInterface: mlootABI,
functionName: 'getWaist',
args: [param],
},
],
isDataEqual: (prev, next) => prev === next,
})
}
```

### staleTime (optional)

Time (in ms) after data is considered stale. If set to `Infinity` the data will never be considered stale. Defaults to `0`.
Expand Down
17 changes: 17 additions & 0 deletions docs/pages/docs/hooks/useContractRead.en-US.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,23 @@ function App() {
}
```

### isDataEqual (optional)

Determines if the data has changed or not. Defaults to `deepEqual`.

```tsx {11}
import { useContractRead } from 'wagmi'

function App() {
const contractRead = useContractRead({
addressOrName: '0xecb504d39723b0be0e3a9aa33d646642d1051ee1',
contractInterface: wagmigotchiABI,
functionName: 'getHunger',
isDataEqual: (prev, next) => prev === next,
})
}
```

### staleTime (optional)

Time (in ms) after data is considered stale. If set to `Infinity` the data will never be considered stale. Defaults to `0`.
Expand Down
24 changes: 24 additions & 0 deletions docs/pages/docs/hooks/useContractReads.en-US.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,30 @@ function App() {
}
```

### isDataEqual (optional)

Determines if the data has changed or not. Defaults to `deepEqual`.

```tsx {15}
import { useContractReads } from 'wagmi'

function App() {
const { data, isError, isLoading } = useContractReads({
contracts: [
{
...wagmigotchiContract,
functionName: 'getAlive',
},
{
...wagmigotchiContract,
functionName: 'getBoredom',
},
],
isDataEqual: (prev, next) => prev === next,
})
}
```

### staleTime (optional)

Time (in ms) after data is considered stale. If set to `Infinity` the data will never be considered stale. Defaults to `0`.
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/actions/contracts/multicall.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ describe('multicall', () => {
"hex": "0x05a6db",
"type": "BigNumber",
},
undefined,
null,
]
`)
})
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/actions/contracts/multicall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export async function multicall<Data extends any[] = Result[]>({
...params,
)) as AggregateResult
return results.map(({ returnData, success }, i) => {
if (!success) return undefined
if (!success) return null
const { addressOrName, contractInterface, functionName } = <
MulticallContract
>contracts[i]
Expand All @@ -103,7 +103,7 @@ export async function multicall<Data extends any[] = Result[]>({
})
if (!allowFailure) throw err
console.warn(err.message)
return undefined
return null
}

const contract = getContract({
Expand All @@ -118,7 +118,7 @@ export async function multicall<Data extends any[] = Result[]>({
return Array.isArray(result) && result.length === 1 ? result[0] : result
} catch (err) {
if (!allowFailure) throw err
return undefined
return null
}
}) as Data
}
2 changes: 1 addition & 1 deletion packages/core/src/actions/contracts/readContracts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ describe('readContracts', () => {
"hex": "0x05a6db",
"type": "BigNumber",
},
undefined,
null,
]
`)
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {

import { InfiniteQueryConfig, QueryFunctionArgs } from '../../types'
import { useInfiniteQuery } from '../utils'
import { deepEqual } from '../../utils'

export type UseContractInfiniteReadsConfig<TPageParam = any> =
InfiniteQueryConfig<ReadContractResult, Error> &
Expand Down Expand Up @@ -77,6 +78,7 @@ export function useContractInfiniteReads<TPageParam = any>({
contracts,
enabled: enabled_ = true,
getNextPageParam,
isDataEqual = deepEqual,
keepPreviousData,
onError,
onSettled,
Expand All @@ -99,8 +101,9 @@ export function useContractInfiniteReads<TPageParam = any>({
return useInfiniteQuery(queryKey_, queryFn({ contracts }), {
cacheTime,
enabled,
keepPreviousData,
getNextPageParam,
isDataEqual,
keepPreviousData,
select,
staleTime,
suspense,
Expand Down
40 changes: 6 additions & 34 deletions packages/react/src/hooks/contracts/useContractRead.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@ import {
ReadContractConfig,
ReadContractResult,
readContract,
watchReadContract,
} from '@wagmi/core'
import { hashQueryKey, useQueryClient } from 'react-query'
import { hashQueryKey } from 'react-query'

import { QueryConfig, QueryFunctionArgs } from '../../types'
import { parseContractResult } from '../../utils'
import { deepEqual, parseContractResult } from '../../utils'
import { useBlockNumber } from '../network-status'
import { useChainId, useQuery } from '../utils'
import { useChainId, useInvalidateOnBlock, useQuery } from '../utils'

type UseContractReadArgs = ReadContractConfig & {
/** If set to `true`, the cache will depend on the block number */
Expand Down Expand Up @@ -76,6 +75,7 @@ export function useContractRead({
cacheOnBlock = false,
cacheTime,
enabled: enabled_ = true,
isDataEqual = deepEqual,
select,
staleTime,
suspense,
Expand Down Expand Up @@ -121,40 +121,12 @@ export function useContractRead({
return enabled
}, [addressOrName, blockNumber, cacheOnBlock, enabled_, functionName])

const client = useQueryClient()
React.useEffect(() => {
if (enabled) {
const unwatch = watchReadContract(
{
addressOrName,
args,
chainId,
contractInterface,
functionName,
overrides,
listenToBlock: watch && !cacheOnBlock,
},
(result) => client.setQueryData(queryKey_, result),
)
return unwatch
}
}, [
addressOrName,
args,
cacheOnBlock,
chainId,
client,
contractInterface,
enabled,
functionName,
overrides,
queryKey_,
watch,
])
useInvalidateOnBlock({ enabled: watch && !cacheOnBlock, queryKey: queryKey_ })
Copy link
Member Author

@jxom jxom Jul 4, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The old implementation was refetching on provider changes (as well as block number changes), but we are already checking for provider changes in our query key (via chainId), so it was double fetching. We still want to watch on block number, so I have refactored this to "invalidate on block" if watch & !cacheOnBlock is truthy.


return useQuery(queryKey_, queryFn, {
cacheTime,
enabled,
isDataEqual,
queryKeyHashFn,
select: (data) => {
const result = parseContractResult({
Expand Down
24 changes: 6 additions & 18 deletions packages/react/src/hooks/contracts/useContractReads.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import * as React from 'react'
import { hashQueryKey, useQueryClient } from 'react-query'
import { hashQueryKey } from 'react-query'
import {
ReadContractsConfig,
ReadContractsResult,
readContracts,
watchReadContracts,
} from '@wagmi/core'

import { QueryConfig, QueryFunctionArgs } from '../../types'
import { useBlockNumber } from '../network-status'
import { useChainId, useQuery } from '../utils'
import { parseContractResult } from '../../utils'
import { useChainId, useInvalidateOnBlock, useQuery } from '../utils'
import { deepEqual, parseContractResult } from '../../utils'

export type UseContractReadsConfig = QueryConfig<ReadContractsResult, Error> &
ReadContractsConfig & {
Expand Down Expand Up @@ -63,6 +62,7 @@ export function useContractReads({
contracts,
overrides,
enabled: enabled_ = true,
isDataEqual = deepEqual,
keepPreviousData,
onError,
onSettled,
Expand Down Expand Up @@ -93,24 +93,12 @@ export function useContractReads({
return enabled
}, [blockNumber, cacheOnBlock, contracts, enabled_])

const client = useQueryClient()
React.useEffect(() => {
if (enabled) {
const unwatch = watchReadContracts(
{
contracts,
overrides,
listenToBlock: watch && !cacheOnBlock,
},
(result) => client.setQueryData(queryKey_, result),
)
return unwatch
}
}, [cacheOnBlock, client, contracts, enabled, overrides, queryKey_, watch])
useInvalidateOnBlock({ enabled: watch && !cacheOnBlock, queryKey: queryKey_ })

return useQuery(queryKey_, queryFn, {
cacheTime,
enabled,
isDataEqual,
keepPreviousData,
queryKeyHashFn,
staleTime,
Expand Down
1 change: 1 addition & 0 deletions packages/react/src/hooks/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export { useBaseQuery, useQuery, useInfiniteQuery } from './query'
export { useChainId } from './useChainId'
export { useForceUpdate } from './useForceUpdate'
export { useInvalidateOnBlock } from './useInvalidateOnBlock'
export { useSyncExternalStore } from './useSyncExternalStore'
export { useSyncExternalStoreWithTracked } from './useSyncExternalStoreWithTracked'
30 changes: 30 additions & 0 deletions packages/react/src/hooks/utils/useInvalidateOnBlock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import * as React from 'react'
import { QueryKey, useQueryClient } from 'react-query'

import { useBlockNumber } from '../network-status'

export function useInvalidateOnBlock({
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Think it's useful to have a basic test that checks the query cache between new blocks?

Not easy to do with our current testing setup, but maybe at least we should add a test.todo.

enabled,
queryKey,
}: {
enabled?: boolean
queryKey: QueryKey
}) {
const { data: blockNumber } = useBlockNumber({
enabled,
watch: enabled,
})
const queryClient = useQueryClient()

const startBlock = React.useRef<number>()
React.useEffect(() => {
if (!enabled) return
if (blockNumber === startBlock.current) return
if (!startBlock.current) {
startBlock.current = blockNumber
return
}

queryClient.invalidateQueries(queryKey)
}, [blockNumber, enabled, queryClient, queryKey])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If useBlockNumbers implementation was updated slightly, we could use the onSuccess callback instead of a separate effect here.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea! Updated, and now the implementation is more basic 👌

}
2 changes: 2 additions & 0 deletions packages/react/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export type QueryConfig<Data, Error> = Pick<
UseQueryOptions<Data, Error>,
| 'cacheTime'
| 'enabled'
| 'isDataEqual'
| 'keepPreviousData'
| 'staleTime'
| 'select'
Expand All @@ -26,6 +27,7 @@ export type InfiniteQueryConfig<Data, Error> = Pick<
| 'cacheTime'
| 'enabled'
| 'getNextPageParam'
| 'isDataEqual'
| 'keepPreviousData'
| 'select'
| 'staleTime'
Expand Down