Web3js – Can’t Get Info: web3.eth.getAccounts Returns Undefined

frontendmetamaskreacttypescriptweb3js

I'm trying to connect to the blockchain via web3 and metamask and the web3.eth.getAccounts() method is returning undefined, however window.ethereum.request({ method: 'eth_requestAccounts' }) returns an array with the accounts.

This is my code:

const getWeb3 = () : Promise<Web3> =>
  new Promise<Web3>((resolve, reject) => {
    // Wait for loading completion to avoid race conditions with web3 injection timing.
    window.addEventListener("load", async () => {
      // Modern dapp browsers...
      if (window.ethereum) {
        const web3 = new Web3(window.ethereum);
        
        try {
          // Request account access if needed
            const test = await window.ethereum.request({ method: 'eth_requestAccounts' });
            console.log(test)// ["0x3b6f82ad02bf6820fe7062ae08817f54467bfb2a"]
         
          const accounts = await web3.eth.getAccounts();
          console.log(accounts) // undefined

          resolve(web3);
        } catch (error) {
          reject("User denied account access. " + error);
          console.log("User denied account access. " + error)
        }
      }
      // Legacy dapp browsers...
      else if (window.web3) {
        // Use Mist/MetaMask's provider.
        const web3 = window.web3;
        console.log("Injected web3 detected.");
        resolve(web3);
      }
      // Fallback to localhost; use dev console port by default...
      else {
        const provider = new Web3.providers.HttpProvider(
          "http://127.0.0.1:8545"
        );
        const web3 = new Web3(provider);
        console.log("No web3 instance injected, using Local web3.");
        resolve(web3);
      }
    });
  });

I need to use resolved web3 in another file, but right now everything that I try to access is returning undefined, for example, await web3.eth.net.getId();.

Best Answer

I end up solving this error by changing the version of web3, I was in version 0.20.x, and I changed it to the latest version, which was 1.4.0.

Related Topic