Stage 8: Events

Video Tutorial

1. Add an event listener for when tokens are transferred and reload the account’s balances when this event is caught, line 76-79 - Add this code within the loadEventListeners() function

this.state.token.Transfer().watch((err, res) => {
  console.log(`Tokens Transferred! TxHash: ${res.transactionHash} \n ${JSON.stringify(res.args)}`);
  this.loadAccountBalances(this.web3.eth.accounts[this.state.defaultAccount]);
});

2. Load the contract events, line 51 - The loadEventListeners function must be called initially to create these listeners - Do so from within the componentDidMount() function

this.loadEventListeners();

Important

This call must come after the token object is 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]);
    this.loadEventListeners();

    [...]
  }
  1. Buy tokens and view the log confirmation in the developer console and token and ETH balance updated dynamically!