1

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

1 Answer 1

3

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.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.