Not able to trigger function from event

Viewed 439

I am not a skilled react programmer but still hope someone would care to explain what I am missing:

What I want I would like to change accounts in Metamask, detect the "accountsChanged" event, and trigger the testFunction.

What works I am able to trigger the testFunction by clicking the test function button. I can detect account change (for some reason it is detected around 5 times every time I change).

What does not work I am not able to trigger the testFunction upon account change and get the message TypeError: this.testFunction is not a function

Suspect there is something fundamental about react I am missing here...Thanks for all replies!

class App extends Component {
   ...
   componentDidMount = async () => {
      ...
   };

   testFunction = async =>{
      console.log("triggered the test function");
   };

   render() {
    window.ethereum.on('accountsChanged', function (accounts) {
      console.log("account change detected");
      this.testFunction(); --> this is not working
    });

     return (
         <div className="App">
           <button type="button" onClick={this.testFunction}>test function</button>
         </div>
       );
     }
  }
1 Answers

You need to convert your normal function to arrow function. Because normal function derives this from the object which is calling it, but arrow function derives it's this from surrounding scope, hence in arrow function this will point to your class and will have access to the methods.

window.ethereum.on('accountsChanged', accounts => {

Also, you can continue using normal function, but in that case you can store the this in some other variable like that' or 'self and use it inside the normal function to call the methods of the class.

let that = this;
window.ethereum.on('accountsChanged', function(accounts){
 that.testFunction() //this will work
Related