Getting balance for wallet in React using Web3

394 views Asked by At

React newbie here. Have an issue starting out, specifically with getting the balance of an address attached to a connected wallet.

import "./App.css";
import React, { useState } from "react";
import { ethers } from "ethers";
import web3 from "web3";

function App() {
  const [walletAddress, setWalletAddress] = useState("");

  async function requestAccount() {
    console.log("Requesting account...");
    if (window.ethereum) {
      console.log("Metamask Wallet Detected");
      try {
        const accounts = await window.ethereum.request({
          method: "eth_requestAccounts",
        });
        setWalletAddress(accounts[0]);
        console.log(walletAddress);
      } catch (error) {
        console.log("Error connecting Wallet");
      }
    } else {
      console.log("Metamask Wallet Absent");
    }
  }

  async function getBalance() {
    const accounts3 = await window.ethereum.request({
      method: "eth_requestAccounts",
    });
    console.log(accounts3[0]);
    const balanceInWei = web3.eth.getBalance(walletAddress);
    console.log(balanceInWei);
  }

  return (
    <div className="App">
      <header className="App-header">
        <button onClick={requestAccount}>Connect Metamask Wallet</button>
        <h3>Wallet Address: {walletAddress}</h3>
        <h2>Account Balance</h2>
        <button onClick={getBalance}>on</button>
      </header>
    </div>
  );
}

export default App;

I already figured out how to fetch the address but for some reason can't find how to get the balance, I see different results everywhere.

0

There are 0 answers