3.7 KiB
title, description
| title | description |
|---|---|
| useWriteContract | Action for executing a write function on a contract. |
useWriteContract
Action for executing a write function on a contract.
A "write" function on a Solidity contract modifies the state of the blockchain. These types of functions require gas to be executed, hence a transaction is broadcasted in order to change the state.
Import
import { useWriteContract } from 'wagmi'
Usage
::: code-group
import { useWriteContract } from 'wagmi'
import { abi } from './abi'
function App() {
const writeContract = useWriteContract()
return (
<button
onClick={() =>
writeContract.mutate({
abi,
address: '0x6b175474e89094c44da98b954eedeac495271d0f',
functionName: 'transferFrom',
args: [
'0xd2135CfB216b74109775236E36d4b433F1DF507B',
'0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
123n,
],
})
}
>
Transfer
</button>
)
}
<<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] :::
Synchronous Usage
If you want to wait for the transaction to be included in a block, you can use useWriteContractSync:
::: code-group
import { useWriteContractSync } from 'wagmi'
import { abi } from './abi'
function App() {
const writeContractSync = useWriteContractSync()
return (
<button
onClick={() =>
writeContractSync.mutate({
abi,
address: '0x6b175474e89094c44da98b954eedeac495271d0f',
functionName: 'transferFrom',
args: [
'0xd2135CfB216b74109775236E36d4b433F1DF507B',
'0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
123n,
],
})
}
>
Transfer
</button>
)
}
<<< @/snippets/abi-write.ts[abi.ts] <<< @/snippets/react/config.ts[config.ts] :::
Parameters
import { type UseWriteContractParameters } from 'wagmi'
config
Config | undefined
Config to use instead of retrieving from the nearest WagmiProvider.
::: code-group
import { useWriteContract } from 'wagmi'
import { config } from './config' // [!code focus]
function App() {
const writeContract = useWriteContract({
config, // [!code focus]
})
}
<<< @/snippets/react/config.ts[config.ts] :::
Return Type
import { type UseWriteContractReturnType } from 'wagmi'
The return type's data property is inferrable via the combination of abi, functionName, and args. Check out the TypeScript docs for more info.
Type Inference
With abi setup correctly, TypeScript will infer the correct types for functionName, args, and the value. See the Wagmi TypeScript docs for more information.