How to change a React button based on a successful smart contract function call?

What is the best way to effectively change a button based on a successful smart contract function call in React?
Hereā€™s what I am doing:
1.Button Approve calls a function and uses useWeb3ExecuteFunction to call a smart contract with fetch: approvalFetch().
2. Then I am using useEffect to call another function fetch: checkApprovedFetch to verify if approval is true. This returns a true or false value. Using this I am changing a useState var traitsApproved and turning it from false to true.
3. In this way I am trying to change the buttonā€™s text using {traitsApproved===false?'Approve My Traits':'Traits Approved'}

However this isnā€™t working because obviously there is a lag when user approves transaction in wallet etc. So even though Iā€™m using useEffect I am unable to ensure that my useState var changes from false to true at the correct time only after function is successfully called and wallet transaction occurs.

What is the best way to change state on contract function call and ensure that state is changed only after the function has been successfully called (after the wallet txn etc is completed).

My contract function:

const { data: approvalData, error: approvalError, fetch: approvalFetch, isFetching: approvalFetching, isLoading: approvalLoading } = useWeb3ExecuteFunction({
        abi: spotTraitsAbiFuji,
        contractAddress: spotTraitsContractFuji,
        functionName: "setApprovalForAll",
        params: {
        operator: spotNFTContractFuji,
        approved: true
             },
         });

@PatrickAlphaC @orangemat I see you have something similar here: Best way to listen for events in react-moralis - Moralis - Moralis Forum. Will this help me?

Hey, check Patrickā€™s answer in that post. It will 100% help your use-case. His code makes it so that your button change will only trigger once 1 confirmation has happened instead of firing once the user clicks approve.

3 Likes

UPDATE:
I have documented my approach to this here:

1 Like