React Hook for Dapps | Contract Initialization.

Cut Outs
2 min readDec 8, 2021

--

This hook is primarily used to initialize a contract that will auto flip web3 between metamask provider & http provider depending on whether wallet is connected or disconnected or on a different chain all together.

— From Dev Team of Cut Outs, Balloons, Cryptostamping

For implementing this, you would be needing to import the source code of hook snippet & RPCURL of the chain you deployed in.

import { useContract } from "react-hooks/useContract";

const RPCURL;
const { web3, contract, setContractParams } = useContract(RPCURL);

Before you can use your contract methods you need to initialize the contract and for that you need to pass the following three params.

  • ABI_DATA is a JSON array compiled from your contract.
  • TOKEN_ADDRESS is the token address of your deployed contract.
  • CHAIN_ID is the standard chain ID of the block chain you deployed on. you can get it from https://chainlist.org
const ABI_DATA;
const TOKEN_ADDRESS;
const CHAIN_ID;
/* auto intialise on window load */
useEffect = (() => {
setContractParams({
abi: ABI_DATA,
token_address: TOKEN_ADDRESS,
chain_id: CHAIN_ID
});
},[])

And then you can call any contract methods from anywhere.

Note that even if the user is on a different chain or not connected, you will still be able to make read calls from contract because it will auto flip to http provider.

const mintTokenCall = () => {
contract?
.methods
.mintToken(TOKEN_URL)
.send({
from: window.ethereum?.selectedAddress,
value: VALUE
})
.once("transactionHash", (hash) => {
setTxProgress("Tx approved");
})
.then((tx) => {
setTxProgress("Tx processed");
})
.catch((err) => {
setTxProgress("Tx unapproved or canceled");
})
}

That's it, with 3 steps you would be able to start doing all the web3 magic with contracts.

The following snippet belongs to one of the many useful react-hooks for DApp developers. To contribute or explore more check here on github.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Cut Outs
Cut Outs

Written by Cut Outs

The NFT filter in digital world.

No responses yet

Write a response