Web3.js and React – How to Map Web3 to a React.js State

dapp-developmentdappsjavascriptreactweb3js

How would you map a changing variable from web3 to react.js component?
Example:

class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      blockNumber: web3.eth.blockNumber,
    }
  }

  render() {
    return(
      {this.state.blockNumber}
    )
  }
}

What would be the best practice without using setTimeout/requestAnimationFrame /setInterval

Best Answer

I figured it out by doing the following:

const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
const abi = [{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"payable":false,"type":"fallback"}];
const address = "0x3E2A850420e024d2f269d45F85a24Dc6F586277D";
const deployedContract = web3.eth.contract(abi).at(address);
const filter = web3.eth.filter('latest');

class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      blockNumber: web3.eth.blockNumber,
      ...deployedContract
    }
  }
  componentDidMount(){
    filter.watch((error, result) =>{
      const block = web3.eth.getBlock(result, true);
      this.setState({blockNumber: block.number});
    });
  }

so that way, every time when you have a new block, your react component will re-render itself, so you will always get new values from your contract.

Related Topic