Skip to content

Instantly share code, notes, and snippets.

@MagRelo
Last active December 5, 2017 20:11
Show Gist options
  • Save MagRelo/d806cf43d0e733028c021029eddc216d to your computer and use it in GitHub Desktop.
Save MagRelo/d806cf43d0e733028c021029eddc216d to your computer and use it in GitHub Desktop.
Load ethereum contract data into react state using web3
import React, { Component } from 'react'
import { Link } from 'react-router'
// JSON file that describe's the contract's metadata. Created during the contract 'compile' step.
import ExampleContract from '../../../build/contracts/example.json'
class FormComponent extends Component {
constructor(props) {
super(props)
this.state = {
loading: true,
exchangeRate: 0,
balance: 0,
owner: 0x0
}
}
componentWillMount(){
// get USD exchange rate for display
fetch("https://api.coinmarketcap.com/v1/ticker/ethereum/?convert=USD")
.then(res => {return res.json()})
.then(data => {
this.setState({
exchangeRate: parseInt(data[0].price_usd, 10)
});
// check for props: web3Instance, contractId
if(this.props.web3.web3Instance){
this.loadContract(this.props.contractId)
} else {
setTimeout(() => {
this.loadContract(this.props.contractId)
}, 1500)
}
}
loadContract(contractId){
let web3 = this.props.web3.web3Instance
if(web3){
const contractInstance = web3.eth.contract(ExampleContract.abi).at(contractId)
this.setState({contractInstance: web3.eth.contract(ExampleContract.abi).at(this.state.contractInstanceAddress)})
// map the contract's getter functions to the fieldnames you want in "this.state"
const functionArray = [
{function: 'getContractBalance', state: 'balance'},
{function: 'getOwner', state: 'owner'},
]
// exectute getter fuctions
functionArray.map(item => {
this.state.contractInstance[item.function]((error, response) => {this.handleCallback(error, response, item.state)})
})
this.setState({loading: false})
} else {
console.log('Error: No web3')
}
}
handleCallback(error, response, feildName){
if(error){
return console.log('feildName:', error)
}
if(response){
let update = {}
if(typeof(response) === 'object'){
update[feildName + '_big'] = response
update[feildName] = response.toNumber()
} else {
update[feildName] = response
}
this.setState(update)
}
}
round(value, places){
places = places || 4
return +(Math.round(value + "e+" + places) + "e-" + places);
}
displayWei(wei){
return 'Ξ' + this.round(web3.fromWei(wei, 'ether'), 7) + ' ETH ($' +
this.round(this.state.exchangeRate * web3.fromWei(wei, 'ether')) + ' USD)'
}
render() {
return(
<main className="">
{this.state.loading ? <p>loading</p> :
<div>
<h1>Contract Details</h1>
<p>Contract balance: {this.displayWei(this.state.balance)}</p>
<p>Contract Owner: &nbsp;
<a href={"https://rinkeby.etherscan.io/address/" + this.state.owner}
target="_blank">{this.state.owner}
</a>
</p>
</div>
</main>
)
}
}
export default FormComponent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment