Using “React Query” to mutate smart contracts (part 2)
NOTE: This series of articles use TypeChain to make strongly-typed calls to Ethereum. Please check its documentation and discussion board to learn how to set it up. It’s also assumed some knowledge of React Query.
In my previous post I created a custom hook that wraps the following code:
This method actually encapsulates two steps:
await contract.pause()returns a
await tx.wait()returns a
ContractTransaction contains information about the transaction before its even validated. The custom hook we have now does not give us access it.
To improve all my mutation hooks that perform a transaction I created the following hook extension:
useMutation to deal with a transaction execution. It takes as
mutationFn a method that returns
ContractTransaction, which is the first line in the
pause() method. The extension automatically calls the
tx.wait(). The extension also allows the use of a
onTransaction callback that receive the
ContractTransaction as a parameter.
This means we can now refactor the
usePause() hook from the previous post to the following:
The following changes occurred:
optionstype is now
mutationFnis now only
contract => contract.pause().
Now the custom hook can be used as follow:
Notice that now there is a
onTransaction callback that is called after the user approves the transaction on the wallet.
This new callback has access to the transaction hash, and much more info, so we can, for example, show a link to the transaction on a block explorer like etherscan.
The use of
useTransactionMutation together with the
useQuery as explained on previous posts, allows reactive and fail proof frontends.
I hope you found this series to be helpful…
Previous: Using “React Query” to mutate smart contracts (part 1)