Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Evirtual opened this issue Jun 28, 2024 · 1 comment

Comments

@Evirtual
Copy link

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
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants