5

I am trying to watch a Solidity event in my React app, but I keep getting the following exception error thrown:

TypeError: MyEvent.watch is not a function

I am sure the event is present in MyContract.json. Here is what my code looks like:

componentDidMount = async () => {
    try {
      // Get network provider and web3 instance.
      const web3 = await getWeb3();

      // Get the contract instance.
      const Contract = truffleContract(MyContract);
      Contract.setProvider(web3.currentProvider);
      const contractInstance = await Contract.deployed();

      // Watch for MyEvent
      contractInstance.MyEvent().watch((error, result) => {});


    } catch (error) {
      console.log(error);  // always gives: TypeError: contractInstance.MyEvent(...).watch is not a function
    }
  };

And this is how MyContract.sol code looks like:

pragma solidity ^0.4.24;

contract MyContract {
    event MyEvent();

    function myFunction() public {
        emit MyEvent();
    }
}
  • Can you share the solidity code where you define the event? – Shawn Tabrizi Sep 4 '18 at 17:18
  • I would perform a sanity check and console.log(contractInstance) to see if it looks correct for the contract you are importing. Share details here too :) – Shawn Tabrizi Sep 4 '18 at 17:25
  • If you happen to be using Web3 1.x beta, then the methods have changed. web3js.readthedocs.io/en/1.0/web3-eth-contract.html#events – Rob Hitchens - B9lab Sep 4 '18 at 17:42
  • Yes, this is exactly it! Now however I get the following error instead: Contract.events.MyEvent is not a function – Tarek Sep 4 '18 at 18:42
  • The issue now seems to be that truffle-contract does not support Web3 1.x beta, hence it's not returning a compatible contract object. – Tarek Sep 4 '18 at 19:39
1

Actually, myContract.MyEvent.watch has been changed in Web3 v1. It is now myContract.events.MyEvent

But, event Listing in Web3 v1.x require websokets to be enabled on the connected node. And, Ganache version 6 and bellow does not support websockets. However, websockets is available at version 7; but it is now in alpha version.

So, you can try with Ganache 7. You can also use latest Geth version in developer mode. Or you may explore Drizzle as it is handly in syncing with the blockchain state and this includs events...

References:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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