I'm attempting to use the web3 from MetaMask in a React js app like so:
import Web3 from 'web3';
componentDidMount(){
if (typeof web3 !== 'undefined') {
console.log(web3.currentProvider);
// Use Mist/MetaMask's provider
var web3js = new Web3(web3.currentProvider);
web3.version.getNetwork((err, netId) => {
switch (netId) {
case "1":
console.log('This is mainnet')
break
case "2":
console.log('This is the deprecated Morden test network.')
break
case "3":
console.log('This is the ropsten test network.')
break
case "4":
console.log('This is the Rinkeby test network.')
break
case "42":
console.log('This is the Kovan test network.')
break
default:
console.log('This is an unknown network.')
}
})
} else {
console.log('No web3? You should consider trying MetaMask!')
}
}
This the output I get in the dev console in chrome:
Clearly at some point web3 is being properly defined by MetaMask based on the first two lines but then react throws an error saying web3 isn't defined for the instances it appears inside if(typeof web3 !== 'undefined'). Everything I've tried results in the same error or web3 not loading.