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.
Please note that as of November of 2018, there has been a breaking change to MetaMask where MetaMask will no longer automatically inject web3 into the browser. Instead users must grant the DApp access to their accounts via accepting a prompt dialog created by window.ethereum.enable(). See the below code for handling MetaMask in both modern DApp browsers as well as legacy DApp browsers.
// Modern DApp Browsers
if (window.ethereum) {
web3 = new Web3(window.ethereum);
try {
window.ethereum.enable().then(function() {
// User has allowed account access to DApp...
});
} catch(e) {
// User has denied account access to DApp...
}
}
// Legacy DApp Browsers
else if (window.web3) {
web3 = new Web3(window.web3.currentProvider);
}
// Non-DApp Browsers
else {
alert('You have to install MetaMask !');
}