Frontend
/
Interacting with a contract

Interacting with a contract

The most straight-forward way to interact with a smart contract is to use the useContract hook from wagmi.

import { useContract } from 'wagmi'

const Page = () => {
  const contract = useContract({
    addressOrName: 'your_contracts_address',
    abi: your_contracts_abi,
  })

  // Reading from the contract
  const readGreeting = async () => {
    const greeting = await contract.greeting()
    console.log(`Greeting: ${greeting}`)
  }

  // Writing to the contract
  const setGreeting = async () => {
    const tx = await contract.setGreeting('Hello world')
    const response = await tx.wait()
    console.log(`Transaction response: ${response}`)
  }
}

useContract does not give you access to loading or error states directly via the hook, though. You have to handle all of that 'manually' here. Proceed to the next page to learn about how useContractRead and useContractWrite solve this.

Last updated on June 1, 2022