Why web3.eth.getAccounts().then(console.log) return empty array?
Asked Answered
A

6

8

I got empty array after I tried to web3.eth.getAccounts().then(console.log);and also got a warning which is./node_modules/web3-eth-accounts/src/scrypt.js Critical dependency: the request of a dependency is an expression. In this project I first commanded create-react-app lottery_react and then all I changed in my lottery_react folder are modifying App.js with only one line web3.eth.getAccounts().then(console.log); and creating web3.js file. I can't find what's wrong in these file. Please help!

I've seen this and this but we all face different kinds of problem.

This is my App.js

import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';

import web3 from './web3';

class App extends Component {
  render(){
    web3.eth.getAccounts().then(console.log);
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
      </div>
    );
  }
}

export default App;

This is my web3.js file


import Web3 from 'web3';

const web3 = new Web3(window.web3.currentProvider);

export default web3;
Aneroidograph answered 16/9, 2019 at 7:33 Comment(1)
If you are using Metamask then go to your account settings -> Connection and add localhost. web3.eth.getAccounts() will work thenLynlyncean
D
19

You now need to request permission from the user to get their accounts. So instead of getAccounts(), use requestAccounts():

web3.eth.requestAccounts().then(console.log);
Disentwine answered 14/4, 2020 at 2:27 Comment(4)
This is working on Chrome+Metamask, but not on Opera Mobile with integrated Wallet. What could be the error?Pluralize
In my case the user don't asked for their content, getAccounts() just returns an empty array.Oospore
@Mergasov you misread my answer. I just edited it so people who copy/paste without reading it, copy the right thing.Disentwine
wow Thanks, this worked for me... This should be the accepted answerIdiophone
D
14

It is very simple you just need to enable the Ethereum in the browser, you can do like this: Just add await window.ethereum.enable();

     const getData = async () => {
        const web3 = new Web3(Web3.givenProvider);
        const network = await web3.eth.net.getNetworkType();
        await window.ethereum.enable();
        const accounts = await web3.eth.getAccounts();
        setAccount(accounts[0]);
        console.log("TCL: getData -> network", network);
        console.log("TCL: getData -> accounts", accounts);
      };
Diaspora answered 18/2, 2020 at 13:37 Comment(0)
A
7

Seems that Metamask is no longer exposing accounts by default, so if you want to access them you need to ask permission to the user. You can see the details in this announcement

Long story short, update your web3.js file to this:

import Web3 from 'web3';

const web3 = new Web3(window.web3.currentProvider);

window.addEventListener("load", async () => {
  // Modern dapp browsers...
  if (window.ethereum) {
    window.web3 = new Web3(window.ethereum);
    try {
      // Request account access if needed
      await window.ethereum.enable();
    } catch (error) {
      // User denied account access...
    }
  }
  // Legacy dapp browsers...
  else if (window.web3) {
    window.web3 = new Web3(web3.currentProvider);
  }
  // Non-dapp browsers...
  else {
    console.log("Non-Ethereum browser detected. You should consider trying MetaMask!");
  }
});

export default web3;
Ambulate answered 16/9, 2019 at 11:31 Comment(2)
this worked. It will pop up metamask and ask to connect to the page. after that it will retrieve the account address from metamask.Hygrothermograph
I'm still getting the same errorSunroom
M
3

Instead of const web3 = new Web3(window.web3.currentProvider);, can you try

const web3 = new Web3(new Web3.providers.HttpProvider(`http://127.0.0.1:7545`));

I am assuming you are running ethereum locally on port 7545

Morbidity answered 16/9, 2019 at 9:18 Comment(0)
G
0

Go to your console with press F12 and be careful that in your Localhost tab(for me was localhost:3000) and then write "ethereum.enable().then(console.log)" in your console. then you can connect to meta mask.

Gordie answered 23/2, 2021 at 13:43 Comment(0)
G
0

I'm using MetaMask, and this worked for me. Found it here.

ethereum
  .request({ method: 'eth_accounts' })
  .then((accounts) => { 
     console.log(accounts); 
  })
  .catch((err) => {
    console.error(err);
  });
Grassplot answered 28/11, 2021 at 9:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.