Frontend
/
Reading from a contract

Reading from a smart contract

We make use of the useContractRead hook from wagmi to read from a smart contract.

import { useContractRead } from 'wagmi'

const Page = () => {
  const { data, isError, isLoading } = useContractRead(
    {
      addressOrName: 'your_contracts_address',
      abi: your_contracts_abi,
    },
    'the_contract_method_name'
  )
}

For example, if you want to read the greeting from a Greeter contract:

import { useContractRead } from 'wagmi'

const Page = () => {
  const { data, isError, isLoading } = useContractRead(
    {
      addressOrName: 'greeter_address',
      abi: Greeter_ABI,
    },
    'greeting'
  )

  return <p>Greeting: {data}</p>
}

If you want to programatically read instead of reading on page load, you can use the refetch function directly:

import { useContractRead } from 'wagmi'

const Page = () => {
  const { refetch } = useContractRead(
    {
      addressOrName: 'greeter_address',
      abi: Greeter_ABI,
    },
    'greeting'
  )

  const handleClick = async () => {
    const res = refetch()
    console.log(`Greeting: ${res}`)
  }

  return <button onClick={handleClick}>Read greeting</button>
}
Last updated on June 1, 2022