useNetwork
Hook for switching networks with a connector.
import { useNetwork } from 'wagmi'
Usage
Some wallet apps do not support programmatic network switching and switchNetwork
will be undefined
. For those situations, you can typically switch networks in the wallet app and wagmi will stay up-to-date.
import { useNetwork } from 'wagmi'
function App() {
const {
activeChain,
chains,
error,
isLoading,
pendingChainId,
switchNetwork,
} = useNetwork()
return (
<>
{activeChain && <div>Connected to {activeChain.name}</div>}
{chains.map((x) => (
<button
disabled={!switchNetwork || x.id === activeChain?.id}
key={x.id}
onClick={() => switchNetwork?.(x.id)}
>
{x.name}
{isLoading && pendingChainId === x.id && ' (switching)'}
</button>
))}
<div>{error && error.message}</div>
</>
)
}
Return Value
{
activeChain?: Chain & { unsupported: boolean }
chains: Chain[]
data?: Chain
error?: Error
isError: boolean
isIdle: boolean
isLoading: boolean
isSuccess: boolean
pendingChainId?: number
switchNetwork?: (chainId?: number) => void
switchNetworkAsync?: (chainId?: number) => Promise<Chain>
status: 'idle' | 'error' | 'loading' | 'success'
reset: () => void
}
Configuration
chainId (optional)
Chain id to switch to. Useful if you want to switch to a specific chain, instead of displaying a list.
import { useNetwork } from 'wagmi'
function App() {
const network = useNetwork({
chainId: 69,
})
}
onError (optional)
Function to invoke when an error is thrown while attempting to switch network.
import { useNetwork } from 'wagmi'
function App() {
const network = useNetwork({
onError(error) {
console.log('Error', error)
},
})
}
onMutate (optional)
Function fires before switch network function and is passed same variables switch network function would receive. Value returned from this function will be passed to both onError
and onSettled
functions in event of a switch network failure.
import { useNetwork } from 'wagmi'
function App() {
const network = useNetwork({
onMutate(args) {
console.log('Mutate', args)
},
})
}
onSettled (optional)
Function to invoke when switch network is settled (either successfully switched, or an error has thrown).
import { useNetwork } from 'wagmi'
function App() {
const network = useNetwork({
onSettled(data, error) {
console.log('Settled', { data, error })
},
})
}
onSuccess (optional)
Function to invoke when switch network is successful.
import { useNetwork } from 'wagmi'
function App() {
const network = useNetwork({
onSuccess(data) {
console.log('Success', data)
},
})
}