admin admin
admin admin

Reputation: 85

why is my variable undefined in reactjs with web3

I am trying to use reactJS to show the balance of an Ethereum wallet with web3. My code successfuly gets the balance and outputs it to the console, however when i try to assign it as a variable and display it in html i get the following error: Line 19:37: 'etherval' is not defined no-undef

The script:

import React from 'react';
import Web3 from 'web3'

export default function balances() {

const web3 = new Web3(new Web3.providers.HttpProvider('https://****'));
web3.eth.getBalance("0x****", function(err1, balance) {
{
    console.log(web3.utils.fromWei(balance, "ether") + " ETH")
    const etherval = web3.utils.fromWei(balance, "ether");
  }
})

  return (
    <div className="details">
      <div className="container">
        <div className="row">
          <div className="col-md-12">
                      <h2>Balance: {etherval}</h2>

          </div>
        </div>
      </div>
    </div>
  );
}

i have tried to initialise the variable with let but this produces more errors, how can i fix this?

Upvotes: 1

Views: 990

Answers (2)

Yilmaz
Yilmaz

Reputation: 49263

get the balance in useEffect and set it in state:

import { useEffect,useState } from "react";


const [balance, setBallance] = useState(null)

useEffect(() => {
    const loadBalance = async () => {
      // make sure web3 is properly
      const web3 = new Web3(new Web3.providers.HttpProvider('https://****'));
      const balance = await web3.eth.getBalance(addressHere)
      setBallance(web3.utils.fromWei(balance, "ether"))
    }

    loadBalance()
  }, [])

Upvotes: 0

Deniz Karadağ
Deniz Karadağ

Reputation: 761

import React, {useState} from 'react';
import Web3 from 'web3'

export default function Balances() {

const [balance, setBalance] = useState(0)
const web3 = new Web3(new Web3.providers.HttpProvider('https://****'));
web3.eth.getBalance("0x****", function(err1, balance) {
{
    console.log(web3.utils.fromWei(balance, "ether") + " ETH")
    setBalance(web3.utils.fromWei(balance, "ether"));
  }
})

  return (
    <div className="details">
      <div className="container">
        <div className="row">
          <div className="col-md-12">
                      <h2>Balance: {balance}</h2>

          </div>
        </div>
      </div>
    </div>
  );
}

You can use useState hook and assign the value once you have it. If this version doesn't render the correct amount, you can use useEffect hook also

Upvotes: 1

Related Questions