Contract function call not working inside useEffect

I have a useEffect hook that is called onMount like so:

const { data, runContractFunction, isLoading } = useWeb3Contract({...}

useEffect(() => {
  if (isInitialized)
      runContractFunction() //from useWeb3Contract 
}, [isInitialized])

useEffect(() => {
   console.log(data) // always null unless setting a timeout of 1 sec above
}, [data])

However, the data from useWeb3Contract is always null. If I set a delay on the call by half a second or so then the data is returned correctly. Am I missing something? I would think the isInitialized check would be all that is needed before calling a function. I have also tried awaiting the runContractFunction but that does not change anything.

Depends on the type of function - check this https://ethereum.stackexchange.com/a/88122

As you can see it’s not always possible to get the return value (depends on the type of function) - it’s a weird property of Ethereum

If the link above describes your situation and it’s your contract that you’ve written - try instead of returning a value you can emit an event

Thanks for the quick reply. It is from my own contract – it’s a view function which returns a value. I am able to get the return value, but only if I delay the call by 1 second in that useEffect hook.

Ok yea then it should work I’ll forward to the team

1 Like

runContractFunction() should be async operation :thinking: as reference here (https://docs.moralis.io/moralis-dapp/web3-api/native#runcontractfunction) , so i supposed the data cannot be retrieved immediately, you have to wait for some time to get the data

@ivan I was able to get it working by changing isInitialized to isWeb3Enabled. I’m assuming this is because I am using useWeb3Contract which requires a wallet provider, and isInitialized checks if Moralis is initialized vs isWeb3Enabled checks if a wallet provider is active.

Even when awaiting the call it wouldn’t work, but I figured out what the issue was. Needed to check isWeb3Enabled not isInitialized.

:thinking::thinking::thinking: is isInitialized should be if the web3api is initialized, if you got it working np, it is all good

If you’re trying to get data from a read-only function then you can use useApiContract instead of useWeb3Contract

1 Like