1

I have the following React component:

class Parent extends Component {
  constructor(props) {
    super(props)

    this.state = {
      id: this.props.id,
      age: 0,
      web3: null,
    }
    this.setAge= this.setAge.bind(this)
  }

  componentWillMount() {
    getWeb3
    .then(results => {
      this.setState({
        web3: results.web3
      })
      this.getData()
    })
    .catch(() => {
      console.log('Error finding web3.')
    })
  }

  getData(){
    const contract = require('truffle-contract')
    const book = contract(Book)
    book.setProvider(this.state.web3.currentProvider)

    var bookInstance

    this.state.web3.eth.getAccounts((error, accounts) => {
      book.deployed().then((instance) => {
        bookInstance = instance

        return bookInstance.ageOf.call(this.props.id, {from: accounts[0]})
      }).then((result) => {
        return this.setState({age: result})
      })
    })
  }

setAge() {
    const contract = require('truffle-contract')
    const book = contract(Book)
    book.setProvider(this.state.web3.currentProvider)

    var bookInstance

    this.state.web3.eth.getAccounts((error, accounts) => {
      book.deployed().then((instance) => {
        bookInstance = instance

        return bookInstance.ageOf.call(this.props.id, {from: accounts[0]})
      }).then((result) => {
        return bookInstance.setAge(this.props.id, {from: accounts[0], value: result, gas: 1000000, gasPrice: this.state.web3.toWei(10, 'gwei')})
      })
    })
  })
}

render() {
     return (
        <div>
          <button onClick={this.setAge}>set age</button>
        </div>
      )
    }
}

export default Parent 

I have the function setAge() that fires a Solidity event called ageSet(uint256 id, uint256 age). I want to listen to the event to alert a message of success, but can't figure it out how to incorporate event listening into the code. What would be the best way?

1

https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#events-allevents

You can do this in your componentWillMount for example: Assuming contract is the instance of the deployed contract

    contract.allEvents({
        fromBlock: 'latest',
    }, function (error, event) {
        if (error)
            alert("error while subscribing to event")
        console.log(event)
        }
    })

This will listen for events from the latest block. That means you won't get past events, but there is an api for that too:

https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#getpastevents

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.