Web3js React – How to Query Account Balance Without Metamask in Browser

reactweb3js

I would like to use this code in order to get the account balance and display it on my react app.

  state = {
    croBalance: "",
  };
  async componentDidMount() {
    const balance = await web3.eth.getBalance(
      "0xu28yjy9chxmhiruhgiwgm93h984hmxhumzmr"
    );
    const etherBalance = await web3.utils.fromWei(balance, "ether");
    const finalBalance = etherBalance.substring(0, 6);
    // console.log(balance);

    this.setState({ croBalance: finalBalance });
  }

here is my webb3.js file:

import Web3 from "web3";

window.ethereum.request({ method: "eth_requestAccounts" });

const web3 = new Web3(window.ethereum);

export default web3;

this code hangs when metamask is not on browser like mobile. I would love to be able to query this address without users needing to confirm metamask account.

Best Answer

Hi bro you just need to set the web3 from your react app and dont use metamask web3 . You just need to do this way : const web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/INFURA_ACCESS_TOKEN:8545')) *You need to create an infuria account and add your infuria sting here , after that you will have web3 that work so you could use your function const balance = await web3.eth.getBalance( "0xu28yjy9chxmhiruhgiwgm93h984hmxhumzmr" );

Take a look here :) How to use infura API with web3 js?

Related Topic