-1

i'm currently using a hook to auto switch network when call contract.

import { useCallback, useEffect, useState } from 'react';
import { useWeb3React } from '@web3-react/core';
import { toast } from 'react-toastify';
import { WalletConnect as WalletConnectV2 } from '@web3-react/walletconnect-v2';
import { Network } from '@web3-react/network';
import { getAddChainParameters } from '../connectors/chains';

const useSwitchNetwork = () => {
  const [desiredChainId, setDesiredChainId] = useState(undefined);
  const { connector, chainId } = useWeb3React();
  const [error, setError] = useState(undefined);
  /**
   * When user connects eagerly (`desiredChainId` is undefined) or to the default chain (`desiredChainId` is -1),
   * update the `desiredChainId` value so that <select /> has the right selection.
   */
  useEffect(() => {
    if (chainId && (!desiredChainId || desiredChainId === -1)) {
      setDesiredChainId(chainId);
    }
  }, [desiredChainId, chainId]);

  const switchNetwork = useCallback(
    async (desiredChainId) => {
      setDesiredChainId(desiredChainId);
      try {
        if (
          // If we're already connected to the desired chain, return
          desiredChainId === chainId ||
          // If they want to connect to the default chain and we're already connected, return
          (desiredChainId === -1 && chainId !== undefined)
        ) {
          setError(undefined);
          return;
        }

        if (connector instanceof WalletConnectV2 || connector instanceof Network) {
          await connector.activate(desiredChainId);
        } else {
          await connector.activate(getAddChainParameters(desiredChainId));
        }

        setError(undefined);
      } catch (error) {
        console.log('Error switch: ', error);
        toast.error('Erorrrrrr: ', error);
        setError(error);
      }
    },
    [connector, chainId, setError],
  );

  return { switchNetwork, error };
};

export default useSwitchNetwork;

I follow the example of web3reactcore My version is: "@web3-react/core": "^8.2.0",

when i call to the hook await switchNetwork(chainId); It throw the error:

underlying network changed (event="changed", network={"name":"arbitrum-goerli","chainId":421613,"ensAddress":null,"_defaultProvider":null}, detectedNetwork={"name":"homestead","chainId":1,"ensAddress":"_____"}, code=NETWORK_ERROR, version=providers/5.7.2)

Any one have same issue and how can i fix it. Many thanks to every one who reach this post

0 Answers0