How to get the network ID by a method other than "window.ethereum.on('chainChanged', async (chainId) =>" when changing the network after connecting MetaMask to DApps

If I connect MetaMask to a DApps, even if I change the network, will “await web3.eth.net.getId();” only return the network ID selected when I connected to the DApps?

If I have not connected my MetaMask account to the DApps, when I change the network, “await web3.eth.net.getId();” returns the changed network ID, but if I connect MetaMask to the DApps, “await web3.eth.net.getId();” returns only the network ID selected when connecting to the DApps.

Is there a way to get the changed network ID even after connecting MetaMask to the DApps, other than “window.ethereum.on(‘chainChanged’, async (chainId) =>”?


useEffect(() => {           
     
    if (window.ethereum) {
        checkNetworkAndLoadData();
            
        window.ethereum.on('chainChanged', async (chainId) => {
            console.log("chainId", chainId);
            window.location.reload();
        });
    }

}, []);

const checkNetworkAndLoadData = async () => {
    if (window.ethereum) {
        try {
            const web3 = new Web3(window.ethereum);
            const currentNetworkId = await web3.eth.net.getId();
            console.log("currentNetworkId", currentNetworkId);                
        } catch (error) {
            console.error("An error occurred:", error);
        }
    } 
};`

Hi I found javascript - How to change network in metamask using react js - Stack Overflow did you try using MetaMask API method MetaMask developer documentation

1 Like

Thank you for your reply. :smiling_face_with_three_hearts:

Even if I changed the network after connecting MetaMask to DApps, “window.ethereum.networkVersion” returned the changed network ID as expected.

This is a big discovery, but “window.ethereum.networkVersion” displays the following warning. It does not seem to be a recommended method.

“VM6221:1 MetaMask: ‘ethereum.networkVersion’ is deprecated and may be removed in the future. Please use the ‘net_version’ RPC method instead.”

With the recommended “window.ethereum.request({ method: ‘net_version’ })” and “await ethereum.request({ method: ‘eth_chainId’ });”, if I changed the network after connecting MetaMask to DApps, it only returned the network ID at the time of connection, not the changed network ID.

It seems that “window.ethereum.networkVersion” may be removed, so I would like to know if there is an alternative way to obtain the network ID.

Thanks.

Thanks for more details, could you please check this discussion and maybe add a comment there: Deprecating Legacy Provider Properties, `networkChanged` event, and `send()` `net_version` support · MetaMask/metamask-improvement-proposals · Discussion #23 · GitHub

I added a comment. Thanks.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.