0

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?

1 Answer 1

1

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);
}
1
  • Yeah, this works great. THX!
    – Sayaki
    Jan 19 at 18:51

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.