Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using web3 from MetaMask in React

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:

enter image description here

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.

like image 544
iicaptain Avatar asked Feb 11 '18 18:02

iicaptain


People also ask

Does MetaMask inject web3?

window. web3 into web pages. MetaMask still injects a dummy object at window. web3 , in order to issue warnings when websites attempt to access window.


1 Answers

You should use web3 provider like MetaMask in browser. This is script that I use for web3 detection:

window.addEventListener('load', function () {
    if (typeof web3 !== 'undefined') {        
        window.web3 = new Web3(window.web3.currentProvider)

        if (window.web3.currentProvider.isMetaMask === true) {
            window.web3.eth.getAccounts((error, accounts) => {
                if (accounts.length == 0) {
                    // there is no active accounts in MetaMask
                }
                else {
                    // It's ok
                }
            });
        } else {
            // Another web3 provider
        }
    } else {
        // No web 3 provider
    }    
});
like image 174
YD1m Avatar answered Oct 22 '22 11:10

YD1m