Search code examples
ethereumsolidityweb3js

How to get an account address from Metamask?


accounts[0] returns undefined in this code.

const accounts = await web3.eth.getAccounts()
console.log(accounts[0])

I uninstalled Metamask and reset the account, but that didn't work.

web3 version is web3@1.0.0-beta.37.

Could you give me any advise, why I cannot get an account address from Metamask?


Solution

  • There was a Metamask connection error. I connected to web3 by coding this.

    Web3(window.web3.currentProvider)
    

    However, this code is better for modern wallet.

    web3 = new Web3(window.ethereum)
        window.ethereum.enable().catch(error => {
            // User denied account access
            console.log(error)
        })