Solidity Events – How to Call a Function in Event Callback

eventssolidity

I have a contract that sends an event when the transaction is done. In my React/Web3 application, I'm listening to this event and when it's triggered I would like to run another function.

My code looks like this:

listenToMyEvent = async () => {
    const { accounts, contract } = this.state;
    await contract.events.MyEvent().on("data", async function(evt) {
        console.log(evt);
        await this.getSuccessCount();
    });
}

getSuccessCount = async () => {
    const { contract } = this.state;
    const count = await contract.methods.getCount().call();
    console.log(count);
}

Receiving an event works great. Also method getSuccessCount works well when I invoke it from outside of the event callback. My problem is that when I invoke await getSuccessCount(); from inside of the event callback I'm getting the following error:
Uncaught (in promise) TypeError: this.getSuccessCount is not a function

How can I invoke getSuccessCount from inside of event listener?

Best Answer

When you use this keyword inside a function callback, the scope of this is the function itself. Something like this should work as the scope of this won't conflict inside the callback.

listenToMyEvent = async () => {
    const { accounts, contract } = this.state;
    const getSuccessCount = this.getSuccessCount;
    
    async function eventCallback(event){
        console.log(event);
        await getSuccessCount();
    }
   
    await contract.events.MyEvent().on("data",eventCallback);
}
Related Topic