gnxvw
gnxvw

Reputation: 454

How to show current Metamask account

I want to show current Metamask account, so I set current metamask account like below.

async componentDidMount() {
  const ethaddress = await web3.eth.accounts[0] 
}

<p>{ethaddress}</p>

However, ethaddress never comes up in frontend.

In console command, if I type web3.eth.accounts[0], it shows current metamask account. But if I type ethaddress, it shows undefined.

Are there any suggestions to show the current metamask account?

Upvotes: 1

Views: 775

Answers (2)

Markus Sprunck
Markus Sprunck

Reputation: 184

The following code works well in the web browser with copy-webpack-plugin (v4.6.0), css-loader (v3.2.0); style-loader (v1.0.0), web3 (v1.2.1), webpack (v4.41.0) and webpack-dev-server (v3.8.1).

import {default as Web3} from 'web3';

web3.eth.getAccounts(function (err, accs) {
    if (err != null) {
         self.setStatus("There was an error fetching your accounts");
         return;
    }
    if (accs.length === 0) {
         self.setStatus("Make sure that you installed and started Metamask plugin and reload this page");
         return;
    }
    console.log('Got account: ', accs[0]);
});

But this code just works in the case the user has already been logged in at Metamask plugin when the page loads. It would be helpful to see a more detailed (running) example of your code.

Upvotes: 2

Bernardo Barateiro
Bernardo Barateiro

Reputation: 79

Try to do something like this:

 web3.eth.getCoinbase(function (err, account) {
            if (err === null) {
                App.account = account;
                console.log("account", App.account);
            }
        })

Upvotes: 1

Related Questions