Web3.js: web3 metamask injection and reactjs not working

Created on 2 Nov 2017  路  5Comments  路  Source: ChainSafe/web3.js

Hello folks
I have a react frontend app. I'm declaring web3 the way advised on this github repo:

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

In my componentDidMount of App.js (main component), I run this function:

initWeb3() {

      console.log("what is web3 right now: " + web3);

       if (typeof web3 !== 'undefined') {
         this.web3Provider = web3.currentProvider;
         web3 = new Web3(web3.currentProvider);
      } else {
          this.web3Provider = new Web3.providers.HttpProvider('http://localhost:8545');
          web3 = new Web3(this.web3Provider);
        }
}

The condition if (typeof web3 !== 'undefined') is never true, even when I run metamask.
I tried web3 1.0 and 0.20.0 .. it's always undefined and falls back to the localhost provider.

Am I doing something wrong here?

Most helpful comment

@Jonathanx5 use window.web3. This worked for me.

All 5 comments

Hi, did you succeed ... I have exactly the same problem !

Try removing the var web3 = Web3() line. You are shadowing the global web3 variable.

@Jonathanx5 use window.web3. This worked for me.

Could You Please show me a complete App Component Implemented ?
This could be so useful...
Are you using web3j with the 1.0.0 version ?
Actually my problem is the subscription to event with Metamask on the browser...
Thank for your help

metamask has known problems with events, they're very flaky. Make sure you update to latest web3js and metamask is current. If you want to see a working example you can unbox a truffle box. truffle unbox <box-name>. http://truffleframework.com/boxes/

Was this page helpful?
0 / 5 - 0 ratings