Uniswap / web3-react

A simple, maximally extensible, dependency minimized framework for building modern Ethereum dApps
https://web3-react-mu.vercel.app/
GNU General Public License v3.0
5.56k stars 1.52k forks source link

Issue with useWeb3React chainId property when changing Network in MetaMask mobile (WalletConnect v2 connector) #933

Open Evirtual opened 4 months ago

Evirtual commented 4 months ago

I am experiencing and issue with useWeb3React and WalletConnect v2 connector. Changing network on MetaMask Mobile is not always updating chainId or there is huge delay and when I run electron app, chainId is stale, regardless if I change network on MM Mobile.

m-Jawa-d commented 2 months ago

Possible Solutions

1. Listen to WalletConnect events manually:

You can manually listen to the chainChanged event to ensure that your application updates the chainId when MetaMask changes the network.

Here's how you can do it:

import { useWeb3React } from '@web3-react/core';

function MyComponent() {
  const { connector, chainId, setChainId } = useWeb3React();

  useEffect(() => {
    if (connector && connector.provider) {
      const handleChainChanged = (newChainId) => {
        setChainId(parseInt(newChainId, 16));
      };

      connector.provider.on('chainChanged', handleChainChanged);

      return () => {
        connector.provider.removeListener('chainChanged', handleChainChanged);
      };
    }
  }, [connector]);

  return (
    <div>
      <p>Current Chain ID: {chainId}</p>
    </div>
  );
}

export default MyComponent;

2. Force Re-fetch on Network Change:

Implement a mechanism that forces your app to re-fetch the network and account details when the user switches networks. You can use the useEffect hook to detect changes and trigger a re-fetch.

  if (connector && connector.provider) {
    const handleChainChanged = async () => {
      window.location.reload();
    };

    connector.provider.on('chainChanged', handleChainChanged);

    return () => {
      connector.provider.removeListener('chainChanged', handleChainChanged);
    };
  }
}, [connector]);

it would be more clear if you mention the version of web3-react to get a better solution.