useContractEvent
Hook for subscribing to ethers Contract events.
import { useContractEvent } from 'wagmi'
Usage
The following examples use the ENS Registry contract.
import { useContractEvent } from 'wagmi'
function App() {
useContractEvent({
address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',
abi: ensRegistryABI,
eventName: 'NewOwner',
listener(node, label, owner) {
console.log(node, label, owner)
},
})
}
Configuration
address (optional)
Contract address. If address
is not defined, hook will not run.
import { useContractEvent } from 'wagmi'
function App() {
useContractEvent({
address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',
abi: ensRegistryABI,
eventName: 'NewOwner',
listener(node, label, owner) {
console.log(node, label, owner)
},
})
}
abi (optional)
Contract ABI. If abi
is not defined, hook will not run.
By defining inline or adding a const assertion to abi
, TypeScript will infer the correct types for eventName
and listener
. See the wagmi TypeScript docs for more information.
import { useContractEvent } from 'wagmi'
function App() {
useContractEvent({
address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',
abi: ensRegistryABI,
eventName: 'NewOwner',
listener(node, label, owner) {
console.log(node, label, owner)
},
})
}
eventName (optional)
Name of the event to listen to. If eventName
is not defined, hook will not run.
import { useContractEvent } from 'wagmi'
function App() {
useContractEvent({
address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',
abi: ensRegistryABI,
eventName: 'NewResolver',
listener(node, resolver) {
console.log(node, resolver)
},
})
}
listener
Callback that receives event.
import { useContractEvent } from 'wagmi'
function App() {
useContractEvent({
address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',
abi: ensRegistryABI,
eventName: 'NewOwner',
listener(node, label, owner) {
console.log(node, label, owner)
},
})
}
chainId (optional)
Force a specific chain id. The wagmi Client
's ethers webSocketProvider
must be set up as a chain-aware function for this to work correctly.
import { useContractEvent } from 'wagmi'
function App() {
useContractEvent({
address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',
abi: ensRegistryABI,
eventName: 'NewOwner',
listener(node, label, owner) {
console.log(node, label, owner)
},
chainId: 1,
})
}
once (optional)
Receive only a single event, then stop listener. Defaults to false
.
import { useContractEvent } from 'wagmi'
function App() {
useContractEvent({
address: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',
abi: ensRegistryABI,
eventName: 'NewOwner',
listener(node, label, owner) {
console.log(node, label, owner)
},
once: true,
})
}