0
votes

I'm trying to update the address and balance every time the account is changed in metamask, however only the account is changing and the balance doesn't get updated.

async componentDidMount(){
    let accs = await web3.eth.getAccounts();
    let balance = await web3.eth.getBalance(accs[0]);
    let balanceth = await web3.utils.fromWei(balance,'ether');
    console.log(balanceth+" ether");
    this.setState({ balanceth });
    this.setState({ account:accs[0] });
      window.ethereum.on('accountsChanged',  (accounts) => {

          console.log(accounts[0]);
          this.setState({ account:accounts[0] });
          let acc = this.state.account;
          // Time to reload your interface with accounts[0]!
          web3.eth.getBalance(acc,(err,bal)=> {balance = bal})
          console.log(balance)
          web3.utils.fromWei(balance,'ether',(err,bal)=>{balanceth = bal});
          console.log(acc,balanceth);
          this.setState({ balanceth:balanceth });
  })
  }
1
can you show your html of input field?Tulshi Das

1 Answers

0
votes

I think the problem lies in trying to change the balance inside of a function. So you're not really changing the value of balance you already defined. try:

web3.eth.getBalance(acc,(err,bal)=> {
    this.setState({ balance: bal })
})