2

So I am using the package wagmi.sh and via that I am writing to a very simple contract called the counter program that increments the value by 1 each time I call the function. Now I am able to successfully increment it, however while using use effect , when it waits for the transaction to complete , I want it to fetch the value of the increment. It is unable to do it, not sure why?

'use client'
import { useContractRead,usePrepareContractWrite, useContractWrite  } from "wagmi"
import {useAccount } from "wagmi"
import { useEffect, useState } from "react"
import { useWaitForTransaction } from 'wagmi'

const abi = [
    {
        "inputs": [],
        "stateMutability": "nonpayable",
        "type": "constructor"
    },
    {
        "inputs": [],
        "name": "counter",
        "outputs": [
            {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
            }
        ],
        "stateMutability": "view",
        "type": "function"
    },
    {
        "inputs": [],
        "name": "getCounter",
        "outputs": [
            {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
            }
        ],
        "stateMutability": "view",
        "type": "function"
    },
    {
        "inputs": [],
        "name": "increment",
        "outputs": [],
        "stateMutability": "nonpayable",
        "type": "function"
    }
]

export default function SimpleStorage(){
    const [countervalue,setCounterValue] = useState(0)
    const {address,isConnecting,isDisconnected,isConnected} = useAccount()
    const  [successStatus,setsuccessStatus] = useState(false)
    console.log(isConnected)
    console.log(address)
    const {data:CounterValue,isError,isLoading} = useContractRead({
        address:"0x9a2b8157348F2D04154e8f79b09EB77D2c506A17",
        abi:abi,
        functionName:"getCounter",
    })
    if(!isLoading){
        console.log("The counter value is ",(CounterValue).toString())
    }
    
    const { config:increment, error } = usePrepareContractWrite({
        address: '0x9a2b8157348F2D04154e8f79b09EB77D2c506A17',
        abi: abi,
        functionName: 'increment',
        })
    const {data:value, write,isSuccess } = useContractWrite(increment)
    
    
    const {data:waitTransaction,isFetched} = useWaitForTransaction({confirmations:2,hash:value?.hash})

    if(isFetched === true){
        setsuccessStatus(true)
    }

    useEffect(() => {
        getCounterValue()
    },[successStatus===true])  
      
    
    
    async function getCounterValue(){
        const counter = await CounterValue.toNumber()
        console.log("Runnin the counter script",counter)
        setCounterValue(counter)
        console.log("Updated value is called !")
    }
    
    

    useEffect(() => {
        if(address ){
            getCounterValue()
        }
    },[address]) 
    

    
   

    return (
        <>
            <div>
                <h1>The value of Counter is:- {countervalue}</h1>
                <br></br>
                <button  onClick={() => write?.()}>
                    Increment
                </button>
                
            </div>
        </>
    )
    
}```

2 Answers 2

2

You should add the watch param to the useContractRead hook so that it continously fetches the new value of the counter

const {data:CounterValue,isError,isLoading} = useContractRead({
        address:"0x9a2b8157348F2D04154e8f79b09EB77D2c506A17",
        abi:abi,
        functionName:"getCounter",
        watch: true
    })
2
  • 1
    does it auto update and keep sending the data once received ? Commented Jun 30, 2023 at 11:50
  • 1
    Thank you this worked ! Commented Jun 30, 2023 at 11:54
2

You can use refetch from useContractRead

  const { refetch: refetchProjects } = useContractRead({
    address: contractAddress,
    abi: abi.abi,
    functionName: "getAllProjects",
    walletClient: walletClient,
    onSuccess(data) {
      setAllProjects(data);
    },
    onError(error) {
      showAlert("Error", error);
    },
  });

  useEffect(() => {
    refetchProjects?.();
  }, [isSuccess]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.