Search code examples
reactjsblockchainethereumweb3js

Const cannot define in react


I cannot define const in react.

After start the web browser, I got the error when I type accounts in console command.

>accounts
VM768:1 Uncaught ReferenceError: accounts is not defined
    at <anonymous>:1:1
(anonymous) @ VM768:1

I thought this is Web3 error, so I defined accounts in console command. However I could define accounts.

>const accounts = web3.eth.accounts[0]
<undefined

>accounts
<"0xeb827c448545--------1a7d5ced86ac3"

I want to show the address by this.state.account.

Could you give me any advise, please?

import React, { Component } from 'react';
import Web3 from 'web3';
import './App.css';

class App extends Component {

  conponentWillmount() {
    this.loadBlockchainData()
  }

  async loadBlockchainData() {
    const web3 = new Web3(Web3.givenProvider || "http://localhost:7545")
    const network = await web3.eth.net.getNetworkType()
    console.log("network:", network)
    const accounts = await web3.eth.accounts[0]
    this.state({ account: accounts[0]}) 
    console.log("account:", accounts[0])
    // Fetch Account
  }

  constructor(props) {
    super(props)
    this.state = { account: ''}
  }

  render() {
    return (
      <div className="container">
        <h1>Hello world</h1>
        <p>Your account : {this.state.account} </p>
      </div>
    );
  }
}

export default App;

Solution

  • const accounts = await web3.eth.accounts[0] variable is local to loadBlockchainData method. It cannot be accessed from console command line because only globals are accessible from there.

    In case accounts needs to be debugged in browser dev tools, a breakpoint can be set up inside loadBlockchainData.