useDapp useCall useEffect

202 Views Asked by At

I need call contract function in useEffect

How to get same result with useDapp ? Any example of this case ?

// define standard web3 call
const feth = async (address) => {
  const contract = new.web3.eth.Contract(ContractAddress, ContractABI)
  const response = await contract.methods.getDataByUserAddress(address).call()
  return response
}

// call when page open
useEffect(() => {
    if(isAddress(props.match.params.address))
      fetch(props.match.params.address)
}, [props.match.params.address]);
1

There are 1 best solutions below

4
Pobepto On

If I understand correctly, it is about this library - useDApp.

In your example you use web3.js, but as I understood from the documentation for useDApp, it works with ethers.js.

To use the library you need to install it and ethers:

npm install @usedapp/core ethers

Further it is quite simple, here is a sample from the documentation with some changes for your question:

const UserAddressComponent = (props: { chainId: number, address: string }) => {
  const wethAddress = WETH_ADDRESSES[props.chainId]
  const wethInterface = new utils.Interface(WethAbi)
  const contract = new Contract(wethAddress, wethInterface)

  const { state, send } = useContractFunction(contract, 'getDataByUserAddress')

  useEffect(() => {
    if (isAddress(props.address)) {
      send(props.address)
    }
  }, [props.address]);

  return (
    <div>
      <p>Status: {state.status}</p>
    </div>
  )
}

The basic idea here is that we use the useContractFunction hook which allows us to send a transaction that executes a function of a contract on a blockchain.

To use useContractFunction you must provide a contract object from the ether.js library and a string function name.

It returns an object, which you can destruct and get from there send method and state object:

  • send is used to make requests and matches all arguments to solidity contract arguments.
  • state object can be used to track the status of a transaction.

You can read more about all the hooks and methods in the documentation of the library