web3-react icon indicating copy to clipboard operation
web3-react copied to clipboard

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

Open Evirtual opened this issue 1 year ago • 1 comments

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.

Evirtual avatar Jun 28 '24 06:06 Evirtual

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.

m-Jawa-d avatar Aug 23 '24 07:08 m-Jawa-d