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)
})
The function has its own this
binding, so you cannot access this.state
on the parent. To solve this, you can either:
this
binding:
.on("data", (event) => {
console.log(this.state.users);
})
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
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP