How update change network ID in MetaMask after change network on MetaMask?

37 views Asked by At

What I am trying to do is to change the network from the select list. Then AlpineJS should send a request to MetaMask to switch the network, and this works perfectly. I can detect when the user changes the network on MetaMask, and I can refresh the website, etc. This is my code:

function formTag() {
    return {
      selectedNetwork: null,
       networks: {!! $networks !!},
       changeNetwork() {
       if (!this.selectedNetwork) {
         return;
      }
       if (window.ethereum) {
       window.ethereum.request({
       method: 'wallet_switchEthereumChain',
       params: [{ chainId: this.selectedNetwork }],
      })
      .then((response) => {})
      .catch((error) => {
       console.error('Error while switching networks:', error);
      });
      } else {
       console.error('MetaMask not installed');
      }
      },
       async getNetworkId() {
       try {
       if (!window.ethereum) {
       alert('MetaMask not detected. Please try again from a MetaMask enabled browser.');
       return;
      }
       const web3 = new Web3(window.ethereum);
       this.selectedNetwork = await window.ethereum.request({ method: "eth_chainId" });
console.log(await window.ethereum.request({ method: "eth_chainId" }));
      } catch (error) {
       console.error("Error:", error);
      }
      },
       init() {
       this.getNetworkId();
       window.ethereum.on('chainChanged', (chainId) => {
      /*window.ethereum.request({
       method: 'wallet_switchEthereumChain',
       params: [{ chainId: chainId }],
      })*/
       this.selectedNetwork = chainId;
      });
       window.ethereum.on('accountsChanged', function (accounts) {
       console.log(accounts[0]);
      });
    },
   }
 }

if i keep commented line below, after chnage network on MM i still see old chainID console.log(await window.ethereum.request({ method: "eth_chainId" }));

/*window.ethereum.request({
  method: 'wallet_switchEthereumChain',
  params: [{ chainId: chainId }],
})*/

But if I uncomment the line above, after changing the network in MetaMask, it closes and opens for a second (I think for updating the same network value), and console.log(await window.ethereum.request({ method: "eth_chainId" })); is okay. Why should I update MetaMask after changing the network on MetaMask? Or is other way?

0

There are 0 answers