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?