Search code examples
reactjsweb3js

Why useEffect doesn't set balance on Web3 and React?


 const [ currentBalance, setBalance ] = useState(0);

Inside the login function I have get account and I want to get the balance with:

const onLogin = async (provider) => {
const web3 = new Web3(provider);
const accounts = await web3.eth.getAccounts();
const chainId = await web3.eth.getChainId();

// Comprobamos las cuentas
if(accounts.length === 0) {
  console.log("Por favor, conectate con MetaMask!");
} else if (accounts[0] !== currentAccount) {
  setProvider(provider);
  setWeb3(web3);
  setChainId(chainId);
  setCurrentAccount(accounts[0]);
  setIsConnected(true);
  const respuestaBal = await web3.eth.getBalance(accounts[0]);
  const balance = web3.utils.fromWei(respuestaBal, "ether");
  setBalance(balance);
}
}

The problem is that this balance is never set.

useEffect(() => {
const handleAccountChanged = async (accounts) => {
  if(accounts.length === 0) {
    onLogout();
  } else if (accounts[0] !== currentAccount) {
    setCurrentAccount(accounts[0]);
    const balance = await web3.eth.getBalance(accounts[0]);
    setBalance(balance);
    
    console.log("BALANCE1: ", balance); // Working
    console.log("BALANCE2: ", currentBalance); // Dont working
  }
}

if(isConnected) {
  provider.on("accountsChanged", handleAccountChanged);
}

return () => {
  if(isConnected) {
    provider.removeListener("accountsChanged", handleAccountChanged);
  }
  
}

}, [isConnected])

I have also tried within the useEffect when I make an account change the code if it recognizes it but it does not recognize that "balance change"


Solution

  • const [ currentBalance, setBalance ] = useState(0);
    const getBalance = async () => {
    
        const balance = await web3.eth.getBalance(accounts[0])
        return balance
        
      }
    
    getBalance().then((res) => (setBalance(res)))
    

    Try this.