Situation
I have created a smart contract and imported the abi and contract address into my react application.
I have successfully accessed the methods and options within my react app. I used useEffect with no issues.
Problem
However, I am struggling to get the balance of the contract. I have tried everything I understand with no result.
This code works fine
import web3 from "./web";
import { useState, useEffect } from "react";
import Lottery from "./Lottery";
const [isManager, setManager] = useState(
"<em>Loading manager address...</em>"
);
useEffect(() => {
const getManager = async () => {
const mangWallet = await Lottery.methods.manager().call();
console.log(mangWallet);
setManager(mangWallet);
};
getManager();
}, []);
This does NOT work - the balance remains 0. More importantly, the console log doesn't even show 0. It's as if the entire getBalance function is not running?
const [balance, setBalance] = useState(0);
useEffect(() => {
const getBalance = async () => {
const contBal = await web3.eth.getBalance(Lottery.contract_address);
setBalance(contBal);
console.log(balance);
};
getBalance();
}, []);
A few things to be aware of:
contract_address is holding the smart contract address on-chain, stored in the Lottery.js fileapp.js. Meaning there are two useEffect functions.I'm not sure what your problem. But I think this async const contBal = await web3.eth.getBalance(Lottery.contract_address); can throw exception. So I think you need to add try catch like this:
const [balance, setBalance] = useState(0);
useEffect(() => {
const getBalance = async () => {
try {
const contBal = await web3.eth.getBalance(Lottery.contract_address);
setBalance(contBal);
console.log(balance);
} catch(error) {
console.log(error);
}
};
getBalance();
}, []);
About the console.log(balance), it alway log 0. Because it's behavior of useEffect. So you need to create another useEffect if you want to see the balance value change like this:
useEffect(() => { console.log(balance) }, [balance])