Write to your smart contracts with the useWriteContract
hook.
useWriteContract
hookuseWriteContract
hook allows you to call your public
and external
smart contract functions that write to state and create a permanent modification to the data on chain.
useWriteContract
hook to send transactions to a smart contractuseWriteContract
useWriteContract
hook. You probably won’t want to use this method in production. In the next step-by-step, we’ll show you the [useSimulateContract
] hook, how it works with useWriteContract
, and how you can use it to create a better user experience.Exploring them separately will highlight the functionality provided by the prepare hook.useWriteContract
hook in a similar way to call those functions directly from your app.
TokenInfo
to the project, and a state variable for tokenBalance
.
useReadContract
. You don’t have a function for this directly in your contract, but your contract inherits from the OpenZeppelin ERC20 contract, which has a function called balanceOf
that takes an address and returns the balance for that address.
You’ll need the user’s address to use in args
, which you can conveniently get from the useAccount
hook using the pattern below.
balanceOf
after the user has done something that might change the balance.return
for your component to display this balance to the user:
index.tsx
.
useWriteContract
useWriteContract
hook is configured similarly to the useReadContract
hook, with one important difference. You’ll need to decompose the write
property from the function call. This is a function that you can use to call your smart contract function whenever you’d like!
useReadContract
hook, you can use isPending
and other state helpers to adjust your UI. The name of this one is a little misleading. isPending
will be true
starting from the moment the transaction gets sent to the user’s wallet.
You can use this to nudge them to look to their wallet to complete the transaction. Additionally, add a useEffect
to watch for an error state.
Claim Tokens
button while connected with a wallet that already owns the tokens. The reason this happens is that viem, which underlies wagmi, runs a simulation of the transaction to estimate gas costs. If that simulation fails, it triggers the fail mechanism immediately, rather than allowing the app to send a bad transaction to the blockchain and cost the user gas for a call doomed to fail. You will fix this in the next tutorial.
In the meantime, you’ll need to change to a new wallet or redeploy your contract a couple of times to complete your testing. Do that, and try out the call on a wallet that hasn’t claimed any tokens. Notice that the button is disabled and the text now prompts the user to look to their wallet to approve the transaction.
useWriteContract
hook to call your smart contract functions on demand. You’ve also tested methods to manage the UI/UX experience for your users, based on the state of the transaction, as well as its success or failure.