0

I am collecting a set of previously generated events, based on certain filters/test, and trying to display them on my HTML page. The code I am using to fetch the events is as follows:

var eventList = []
var myEvent = instance.EventName(
    {name: 'test name'}, 
    {fromBlock: 0, toBlock: 'latest'});

    myEvent.watch(function(error, result){
        if(result.args.cost > 100) {
          eventList.push(result);     
        }
    });

When I try to view the values in eventList using console.log(eventList) on Chrome, I get an empty array represented as []. On clicking on the same, the array expands to show the actual values inside. However, this is accompanied by a message on the console stating "Value below was evaluated just now.".

I am unable to get the length of this array or loop over its contents as every time the array is seen as empty. This led me to believe that the values are somehow returned asynchronously by the Web3js watch function (Web3js v0.2.7). I tried converting the array object into a string using JSON.Stringify(), however, it just returns [] instead of the populated array.

What is the reason for this behaviour and how would I convert the array into a concrete object such that I could iterate over its contents?

1

Consider update to Web3js v1.2.0. Assuming that there is no error in the event you are trying to listen, replace this myEvent.watch method for an eventEmitter method to work with promiEvent. As you can check here https://web3js.readthedocs.io/en/v1.2.0/callbacks-promises-events.html?highlight=event%20emitter.

I am also missing how you are dealing with the object return, as it might return a promises (or a promiEvent as mentioned above).

Have a look from the docs:

myContract.events.MyEvent({
filter: {myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...'}, // Using an array means OR: e.g. 20 or 23
fromBlock: 0 }, function(error, event){ console.log(event); })
.on('data', function(event){
    console.log(event); // same results as the optional callback above
})
.on('changed', function(event){
    // remove event from local database
})
.on('error', console.error);

https://web3js.readthedocs.io/en/v1.2.0/web3-eth-contract.html#id36

As you shared just a few lines this is the farthest I can go, but feel free to reach me if you need more help.

I hope this help. Cheers.

0

You are correct with web3js v0.20 event.watch() will listen for new events.

If you want to retrieve existing events you have to use event.get()

const TransferEvent = token.Transfer({}, {fromBlock: 0, toBlock: 'latest'});

TransverEvent.get(function (error, events) {
   if (!error) {
       console.log("Failed: ", error);
       return;
   }
   consolel.log("Events: ", events);
});

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.