phoenixson
phoenixson

Reputation: 117

Issue with Web3 1.1.0

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?

Upvotes: 1

Views: 365

Answers (1)

damianodamiano
damianodamiano

Reputation: 2662

I solved this issue with this code:

web3.eth.getAccounts(function (err, accounts) {
      if (err != null) {
        console.log(err)
      }
      else if (accounts.length === 0) {
        console.log('MetaMask is locked');
      }
      else {
        console.log('MetaMask is unlocked'); 
        console.log(accounts[0]);
      }
    });

Maybe you need also to add ethereum.enable();.

Upvotes: 1

Related Questions