useContractWrite

Generic hook for calling any smart contract function that requires a transaction to take place.

Provide your smart contract instance returned from the useContract hook, along with the name of the function you wish to call on your smart contract as arguments to the hook.

Then call the mutate or mutateAsync function returned by the hook, providing an array of arguments to send to your smart contract function.

If you provide too many or too few arguments, the error property will be populated with an error message.

If your function has no arguments, provide an empty array by calling the function with { args: [] }

If you have cached the ABI of your smart contract using thirdweb generate , the functionName and args parameters are strongly typed according to your smart contract’s ABI.

Example

import {
useContractWrite,
useContract,
Web3Button,
} from "@thirdweb-dev/react";
function App() {
const { contract } = useContract(contractAddress);
const { mutateAsync, isLoading, error } = useContractWrite(
contract,
"setName",
);
return (
<Web3Button
contractAddress={contractAddress}
// Calls the "setName" function on your smart contract with "My Name" as the first argument
action={() => mutateAsync({ args: ["My Name"] })}
>
Send Transaction
</Web3Button>
);
}
function useContractWrite(
contract: TContractInstance extends ValidContractInstance
? RequiredParam<TContractInstance<TContractInstance>>
: TContractAddress extends never
? RequiredParam<
BaseContractForAddress<TContractAddress<TContractAddress>>
>
>
: RequiredParam<SmartContract<BaseContract>>,
functionName: RequiredParam<TFunctionName>,
): UseMutationResult<
Omit<TransactionResultWithMetadata<unknown>, "data">,
unknown,
{ args?: TArgs; overrides?: CallOverrides },
unknown
>;

Parameters

The contract instance of the contract to call a function on

Type

let contract: TContractInstance extends ValidContractInstance
? RequiredParam<TContractInstance<TContractInstance>>
: TContractAddress extends never
? RequiredParam<
BaseContractForAddress<TContractAddress<TContractAddress>>
>
>
: RequiredParam<SmartContract<BaseContract>>;

The name of the function to call in the smart contract.

Type

let functionName: RequiredParam<TFunctionName>;

Returns

let returnType: UseMutationResult<
Omit<TransactionResultWithMetadata<unknown>, "data">,
unknown,
{ args?: TArgs; overrides?: CallOverrides },
unknown
>;

A mutation object that includes the write function to call