Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/sixty-mugs-serve.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"wagmi": minor
---

fix: compute proper chainId value on useReadConstracts to avoid unnecessary queryKey mutations
18 changes: 16 additions & 2 deletions packages/react/src/hooks/useReadContracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type {
ReadContractsErrorType,
ResolvedRegister,
} from '@wagmi/core'
import type { Compute } from '@wagmi/core/internal'
import type { ChainIdParameter, Compute } from '@wagmi/core/internal'
import {
type ReadContractsData,
type ReadContractsOptions,
Expand Down Expand Up @@ -62,10 +62,24 @@ export function useReadContracts<

const config = useConfig(parameters)
const chainId = useChainId({ config })
const contractsChainId: number | undefined = useMemo(() => {
if (contracts.length === 0) return undefined

// Get the chainId of the first contract (if any)
const firstChainId = (contracts[0] as ChainIdParameter<config>).chainId

// If all contracts have the same chainId as the first, return it
const allSameChainId = contracts.every(
(contract: ChainIdParameter<config>) =>
(contract as ChainIdParameter<config>).chainId === firstChainId,
)

return allSameChainId ? firstChainId : undefined
}, [contracts])

const options = readContractsQueryOptions<config, contracts, allowFailure>(
config,
{ ...parameters, chainId },
{ ...parameters, chainId: contractsChainId ?? chainId },
)

const enabled = useMemo(() => {
Expand Down