Contract events: how do I get UI update of smartcontract data

In developing with smart contracts (not specifically OpenZeppelin Contracts or OpenZeppelin SDK) event is used to access data form a smart contract logs. I plan on using polling with setInterval to access event data into my UI.

In practice I run into difficulty in the event parameter syntax, any help would be appreciated. Here is the pattern shown in the web3 docs:

//version 0.2.x:
var event = myContractInstance.myEvent({valueA: 23} [, additionalFilterObject])
// watch for changes
event.watch(function(error, result){
 if (!error)
   console.log(result);
});
// Or pass a callback to start watching immediately
var event = myContractInstance.myEvent([{valueA: 23}] [, additionalFilterObject] , function(error, result){
 if (!error)
   console.log(result);
});

I use truffle to access my contract methods etc… so here is my code whereby I omitte the first parameter since that is optional(?) (Note: NewData is my contract event name)

myContract.deployed().then((instance) => instance.NewData.watch(function(error
, result) { if (!error)
console.log(result)      
this.currentNumber = result;}))

web console error:

Unhandled promise rejection TypeError: missing argument 1 when calling function instance.NewData.watch
1 Like

Hi @Steeve,

Can you use a later version of web3.js e.g. 1.2.4 and try this example?
https://web3js.readthedocs.io/en/v1.2.4/web3-eth-contract.html#id51

I got the event Dapp reactive UI update working by correctly using callback to assign event value to the variable. No need to use SetInterval since events can be tied to reactive UI components.

      myContract.deployed().then((instance) => { 
              instance.NewData().watch((error,result) => { 
        if (!error)
        { 
        this.currentNumber =  result.args.Update;
        } 
        else {
        console.error(error)
        this.message = "Update failed"
         }
       })
     })

Note:

  1. that NewData is my contract event name and Update is my passed contract data.
  2. Yes the web3 synax is for the older version 0.2.0 but will refactor to latest web3
1 Like