7

I am facing some problem with metamask. I ve copied the code below from the metamask documentation to load the web3 but i get always web3.eth.accounts[0] returns undefined when i try to get the account's address even if metamask is connected to ropsten. The same code works with Mist perfectly.

window.addEventListener('load', function() {

    if (typeof web3 !== 'undefined') {
        // Use Mist/MetaMask's provider
        window.web3 = new Web3(web3.currentProvider);
        console.log("Metamask used");
    } else {
        console.log('No web3? You should consider trying MetaMask!')
        // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
        window.web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/token"));
    }

    console.log('test1'+web3.eth.accounts[0]);

});
console.log('test'+web3.eth.accounts[0]);

i get the output of the first log.

Aniket
  • 3,545
  • 2
  • 20
  • 42
Etherkimist
  • 272
  • 3
  • 10
  • this is your code? maybe is a problem of the asynchronous system... Are you using well the callback function :/ ? – Gawey May 31 '17 at 14:45

2 Answers2

11

Metamask does not let you use synchronous functions. Use instead:

web3.eth.getAccounts(function(error, accounts) {
    ...
});

And remove your second log. You only want to do things after you have properly initialised.

0

You can also use await for synchronization.

const getAccount = async () => {
  ...
  const accounts = await web3.eth.getAccounts();
  const account = accounts[0];
  return account;
}
Ice Griffin
  • 183
  • 1
  • 7