1

I got no accounts loaded with code

import Web3 from "web3";

let web3;

// typeof check if variable exists
if (typeof window !== 'undefined' && typeof window.web3 !== 'undefined') {

    web3 = new Web3(window.web3.currentProvider);
    console.log("Metamask used");
    const getAccounts = async () => {
        const accounts = await web3.eth.getAccounts();
        return accounts;
    };

    console.log('first account is ', getAccounts()[0]);
} else {
    console.log('not Metamask');
    const provider = new Web3.providers.HttpProvider(
        'https://rinkeby.infura.io/v3/foo'
    );
    web3 = new Web3(provider);
}

export default web3;

And I got console log:

Metamask used
first account is `undefined`

So I can assume metamask is injected in the window, however no accounts were loaded. (I absolutely had logged in my metamask)

Version:

"next": "^4.1.4",
"web3": "^1.0.0-beta.35"

Have someone encountered the same problem, thanks in advance!

  • I'd suggest to upgrade web3 to version 1.2.x. Did you call ethereum.enable()? Unless your site is approved by the user getAccounts will return nothing. See metamask docs docs.metamask.io/guide/…. – Ismael Apr 2 at 14:00
0

Your getAccounts function returns a Promise object, not an array of accounts.

So the expression getAccounts()[0] is obviously undefined.

You'll need to resolve that promise in order to retrieve the actual array.

For example, using const accounts = await getAccounts(); from inside an async function.

| improve this answer | |
  • hi, goodvib. Should I add another async function below like async () => {await getAccounts()} ? – MJeremy Apr 2 at 3:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.