1

I'm trying to get the network ID from the Web3 object on the client side (i.e. - while running Javascript code in the browser). I have code that confirms that the object exists and it does. I have the Metamask extension installed and configured in Chrome. I have clicked on the extension and I am definitely connected to the Ganache network client (Localhost 8545). However, every time I call **web3.version.getNetwork()** the result is **undefined**. Does anyone know why this is happening and how I can fix it?

UPDATE: I tried the same test with web3.eth.getAccounts() and that too is coming back undefined. I'm guessing I'll get the same result with any of the Web3 methods/properties I try.

    // Make sure the Web3.js object has been defined.
    web3_helpers.web3AndMetamaskCheck();

    if (typeof gameDetailsObj == 'undefined' || gameDetailsObj == null)
        throw new Error(errPrefix + 'The game details object is unassigned.');

    if (typeof currentUserObj == 'undefined' || currentUserObj == null)
        throw new Error(errPrefix + 'The current user object is unassigned.');

    // >>>>> getNetworkCall is ALWAYS 'undefined'.          
    var getNetworkCall = web3.version.getNetwork();
1

Yes, your right it will return undefined. Because web3.version.getNetwork() is not a sync method and it will not return any value. In javascript, If function is not return any method it will init varible is undefined. Refer below code for ref:

web3.version.getNetwork(function(err, networkId){
            switch(networkId){
                case "1":
                    //TODO your logic...
                    break;
                default:
                    //If neteork id is not mattching...
            }
});

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.