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);
}
}
};`