1

I have been having trouble with callbacks in reactjs with web3. In the code below my alert function is properly printing the number of players returned by my contract but otherFuction is not being called and setState is not changing the value printed in my paragraph.

class PracticeComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {players: ""};
  }

  componentWillMount(){

    simpleContract.methods.getPlayerNumber().call(function(error, result){
      alert(result);
      this.otherFunction(result);
    });

  }

  otherFunction(value){
    this.setState({
      players:value
    });
  }

  render() {
    return (
        <div>
          <p> {this.state.players} <p/>
        </div>
    );
}

In previous attempts at a solution I have appended
simpleContract.methods.getPlayerNumber().call() with .then(this.otherfunction) but have not had luck.

Any thoughts? Any pointers?

2

The context of this is lost by using the standard function declaration block. To fix, you have a few options:

(Recommended) Use arrow functions to keep this in reference:

componentWillMount(){
  simpleContract.methods.getPlayerNumber().call((error, result) => {
    alert(result);
    this.otherFunction(result);
  });
}

Chain bind this to the function declaration:

componentWillMount(){
  simpleContract.methods.getPlayerNumber().call(function(error, result){
    alert(result);
    this.otherFunction(result);
  }).bind(this);
}

Create a variable before the function declaration referencing this:

componentWillMount(){
  const _this = this;
  simpleContract.methods.getPlayerNumber().call(function(error, result){
    alert(result);
    _this.otherFunction(result);
  });
}
  • Fixed using method 1! Thanks for your help and time! – Bryan Campbell May 2 '18 at 16:35

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.