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?
constare block scoped, soethervalonly exists inside the getBalance callback.var, that's from an era of JS that we no longer live in. Useletfor values that are going to change, or get assigned later, and useconstfor values that you immediately assign and then never change again. But even if you do that as properly as possible, that won't actually work because your return statement will happen well before you get that value. Thatethervalis state data, and you should be using the useState hook for it.