Stage 6: Load Account Balances

Video Tutorial

  1. Load the default account’s ETH and Token balances, completing the loadAccountBalances function
  • Add tokenBalance to the state, line 24
tokenBalance: 0,
  • Add ethBalance to the state, line 23
ethBalance: 0,

Important

This code below must be placed within the loadAccountBalances function

i.e.

// Load the accounts token and ether balances.
async loadAccountBalances(account) {
  const balance = await this.state.token.balanceOf(account);
  this.setState({ tokenBalance: balance.toNumber() });

  const ethBalance = await this.web3.eth.getBalance(account);
  this.setState({ ethBalance: ethBalance });
}
  • Set the token balance, line 64-65

    const balance = await this.state.token.balanceOf(account);
    this.setState({ tokenBalance: balance.toNumber() });
    
  • Set the eth balance, line 67-68

    const ethBalance = await this.web3.eth.getBalance(account);
    this.setState({ ethBalance: ethBalance });
    
  • Call the loadAccountBalances function when the page initially renders within the componentDidMount function, line 49

    this.loadAccountBalances(this.web3.eth.accounts[0]);
    

    Important

    This code must be placed in the componentDidMount function after the token object has been created.

    i.e.

    async componentDidMount() {
      // Create a web3 connection
      this.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
    
      this.web3.version.getNetwork(async (err, netId) => {
        const tokenAddress = tokenArtifacts.networks[netId].address;
        const token = this.web3.eth.contract(tokenArtifacts.abi).at(tokenAddress);
        this.setState({ token });
        console.log(token);
    
        // Set token symbol below
        const tokenSymbol = await token.symbol();
        this.setState({ tokenSymbol });
    
        // Set wei / token rate below
        const rate = await token.rate();
        this.setState({ rate: rate.toNumber() });
    
        this.loadAccountBalances(this.web3.eth.accounts[0]);
    
        [...]
      }
    
  • Also load the balances whenever a new account is selected in the dropdown, place this line within the handleDropDownChange function, line 94

    this.loadAccountBalances(this.state.availableAccounts[index].key);
    
    • i.e.
    handleDropDownChange = (event, index, defaultAccount) => {
      this.setState({ defaultAccount });
      this.loadAccountBalances(this.state.availableAccounts[index].key);
    }
    
  1. View the default account balances and token information in your browser!