Skip to content

watchChainId

Subscribe to chain ID changes.

Import

ts
import { watchChainId } from '@wagmi/core'

Usage

ts
import { watchChainId } from '@wagmi/core'
import { config } from './config'

const unwatch = watchChainId(config, {
  onChange(chainId) {
    console.log('Chain ID changed!', chainId)
  },
})
unwatch()
ts
import { http, createConfig } from '@wagmi/core'
import { mainnet, sepolia } from '@wagmi/core/chains'

export const config = createConfig({
  chains: [mainnet, sepolia],
  transports: {
    [mainnet.id]: http(),
    [sepolia.id]: http(),
  },
})

Parameters

ts
import { type WatchChainIdParameters } from '@wagmi/core'

onChange

onChange(chainId: GetChainIdReturnType, prevChainId: GetChainIdReturnType): void

Callback function called when chain ID changes.

ts
import { watchChainId } from '@wagmi/core'
import { config } from './config'

const unwatch = watchChainId(config, {
  onChange(chainId) { 
    console.log('Chain ID changed!', chainId)
  },
})
unwatch()
ts
import { http, createConfig } from '@wagmi/core'
import { mainnet, sepolia } from '@wagmi/core/chains'

export const config = createConfig({
  chains: [mainnet, sepolia],
  transports: {
    [mainnet.id]: http(),
    [sepolia.id]: http(),
  },
})

Return Type

ts
import { type WatchChainIdReturnType } from '@wagmi/core'

Function for cleaning up watcher.

Released under the MIT License.