2

Having trouble accessing Metamask's web3 object.

Following the recommended guidelines for using Metamask's injected web3 object https://github.com/MetaMask/faq/blob/master/DEVELOPERS.md#partly_sunny-web3---ethereum-browser-environment-check

Shouldn't this avoid a possible race condition?

 componentDidMount() {
         window.addEventListener('load', function() {

         // Checking if Web3 has been injected by the browser (Mist/MetaMask)
            if (typeof web3 !== 'undefined') {
                 // Use Mist/MetaMask's provider
                 window.web3 = new Web3(web3.currentProvider);
             } else {
                 console.log('No web3? You should consider trying MetaMask!')
                 // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
                 window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
         }
         })
    }

Still...

enter image description here

4

You put the load listener inside the componentDidMount listener, which almost definitely fires later than the load event. Try removing the load listener, the component loading should already wait long enough.

|improve this answer|||||
  • Thanks Dan, works when we move the check to the global scope albeit only by reassigning web3 object to let web3 = window.web which feels like a hack... trying to follow docs as closely as possible, but this is best we can manage atm – Zach_is_my_name Mar 24 '17 at 20:05
  • Accessing window.web3 works for me on the first page load, but fails on page refresh, for the same timing reason you've described. – Danyal Aytekin Oct 12 '17 at 16:42

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.