简体   繁体   中英

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?

I've run into the same issue, i solved 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]);
      }
    });

Makbe you need also to add ethereum.enable(); . Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM