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:

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:

This useTransactionMutation extends 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:

  • The mutationFn is now only contract => contract.pause().
  • Uses useTransactionMutation instead of useMutation.

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)



Principal Engineer @ Farfetch - R&D

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store