1

I'm using metamask to connect to rinkeby network. I can see metamask injects web3 code just fine, still I get the Error: Provider not set or invalid. Here's the js script I wrote.

var Web3 = require('web3');
var web3 = new Web3();

if (typeof web3 !== 'undefined') {
    console.log("Using web3 detected from external source like Metamask");
    web3 = new Web3(web3.setProvider(web3.currentProvider));

} else {
    console.log("Using localhost");
    web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}

var account = web3.eth.accounts[0];

console.log(account);

Here's the error I'm getting

enter image description here

I'm using webpack, web3 0.20.4. How do I solve this?

1

You actually shouldn't be setting a provider within a new Web3 instance if you already have the web3.currentProvider.

Replace:

web3 = new Web3(web3.setProvider(web3.currentProvider));

with:

web3 = new Web3(web3.currentProvider);

Also, do not create the web3 instance before checking for the browser version.

Replace the line:

var web3 = new Web3();

with:

var web3 = window.web3;
  • Thanks it worked. The line var web3 = new Web3(); is used in many tutorials and it worked for them. I'm pretty new to js stuff. Can you tell me what's happening in this var web3 = window.web3; line? – Uchiha Madara Feb 12 '18 at 20:58
  • 1
    @UchihaMadara By using that var web3 = new Web3(), you basically overwrite the option to check for the browsers version. Your typeof web3 !== 'undefined' check would only check the browser/metamask version properly if you did typeof window.web3 !== 'undefined'. It also didn't make much sense to initiate a new Web3 instance on the second line when your if/else statement does it anyways. – ReyHaynes Feb 12 '18 at 21:03
  • @ReyHaynes it doesn't work and even throws an additional error with your suggestions – Vyachaslav Gerchicov May 22 '18 at 8:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.