diff --git a/.changeset/sixty-mugs-serve.md b/.changeset/sixty-mugs-serve.md new file mode 100755 index 0000000000..dcc4324910 --- /dev/null +++ b/.changeset/sixty-mugs-serve.md @@ -0,0 +1,5 @@ +--- +"wagmi": minor +--- + +fix: compute proper chainId value on useReadConstracts to avoid unnecessary queryKey mutations \ No newline at end of file diff --git a/packages/react/src/hooks/useReadContracts.ts b/packages/react/src/hooks/useReadContracts.ts index 7be786c4a8..fd930fdf4a 100644 --- a/packages/react/src/hooks/useReadContracts.ts +++ b/packages/react/src/hooks/useReadContracts.ts @@ -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, @@ -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).chainId + + // If all contracts have the same chainId as the first, return it + const allSameChainId = contracts.every( + (contract: ChainIdParameter) => + (contract as ChainIdParameter).chainId === firstChainId, + ) + + return allSameChainId ? firstChainId : undefined + }, [contracts]) const options = readContractsQueryOptions( config, - { ...parameters, chainId }, + { ...parameters, chainId: contractsChainId ?? chainId }, ) const enabled = useMemo(() => {