Search code examples
reactjsrenderingsetstate

react setstate not rerenering


I have the following:

  onTransfer = async () => {
    this.setState({loading: true});
    try {
      const accounts = await web3.eth.getAccounts();
      await this.props.myData.methods.transferBalanceToOwner().send({
        from: accounts[0]
      });

      let contractBalance;
      await web3.eth.getBalance(this.props.address).then(function(result) {
        contractBalance = web3.utils.fromWei(result);
      });
      console.log('contract balance: ', contractBalance);

      this.setState({ contractBalance });
    } catch (error) {
      console.log('Transfer to owner error: ',error)
    }
    this.setState({loading: false});  
  }

and I have the following in my render()

if (this.state.isOwner) {
  ownerUI = (
    <Container>
      <Divider/>
      <p>Contract balance: {this.state.contractBalance}</p>
      <Button loading={this.state.loading} onClick={this.onTransfer} primary>Transfer Balance</Button>
    </Container>
  )
}

For some reason, the contract balance is not getting update after OnTransfer. Can someone spot what I might be doing wrong? Thanks!


Solution

  • Its not right way to use async/await.

    1. With async/await there is no thenable
    2. Put await statement inside try/catch block for success/error check.

    The correct way to do this.

    let contractBalance;
    
    try {
       //success check
    
      contractBalance = await web3.eth.getBalance(this.props.address)
      this.setState({contractBalance});
    
    }
    catch (rejectedValue) {
      //error check
    
      console.log(rejectedValue)
    }