TransWikia.com

Web3js events and their callback functions are not aware of component state?

Ethereum Asked by fimac on August 26, 2021

I have problem with web3js 1.2.9
Events triggering works fine and data is alright but I cannot figure out how to use component state in this functions that are triggered by event.
I cannot access state of that component where watch event is initialized.

this.state.contract.events.NewUserCreated()
             .on("connected",function (subscriptionId) {console.log("SubscriptionId  ",subscriptionId)})
             .on("data",function (event) {
                 console.log("Event ",event)
                 console.log("Current users")
                 console.log(this.state.users)
        
             })

One Answer

The function has its own this binding, so you cannot access this.state on the parent. To solve this, you can either:

  1. Use an arrow function, since they don't provide their own this binding:
      .on("data", (event) => {
        console.log(this.state.users);
      })
    
  2. Bind the function to the parent's this object:
    function handleData (event) {
      console.log(this.state.users);
    }
    
    //...
      .on("data", handleData.bind(this));
    

You can read more about this in JavaScript on the MDN docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this.

Correct answer by Morten on August 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP