[Ethereum] Issue getting Metamask account using Web3 1.1.0

dapp-developmentweb3js

I am working on a React app which uses a library that has Web3 as a dependency. I had previously been able to the get the current Metamask address with the following code:

 const injectedWeb3 = window.web3 || undefined;

 this.state = {
      web3: injectedWeb3
    };

  getAccount() {
    const { web3 } = this.state;
    if (web3.eth.accounts[0]) return web3.eth.accounts[0];
    throw new Error('Your MetaMask is locked. Unlock it to continue.');
  }

Then I updated that library to its latest version which changed it's Web3 dependency to Web3 1.0 . Now when I run the exact same code I get the following error:

Error: Invalid JSON RPC response: undefined 
TypeError: e is not a function[Learn More] 

Any thoughts as to what might be going on?

Best Answer

Found a workaround for this, you can use window.ethereum.enable() and attach it to the web3.eth.defaultAccount variable,

loadAccount : async () =>{
       window.ethereum.enable().then((account) =>{
           const defaultAccount = account[0]
           web3.eth.defaultAccount = defaultAccount

       })
    }

you can then access the Account ID / Address by using web3.eth.defaultAccount

Related Topic