diff --git a/src/hooks/web3/useSyncNetworkParamWithStore.ts b/src/hooks/web3/useSyncNetworkParamWithStore.ts index 19d8d9eebe..876c009dd5 100644 --- a/src/hooks/web3/useSyncNetworkParamWithStore.ts +++ b/src/hooks/web3/useSyncNetworkParamWithStore.ts @@ -3,6 +3,7 @@ import { useLocation, useNavigate, useParams } from 'react-router-dom' import { NETWORKS_INFO } from 'constants/networks' import { useActiveWeb3React } from 'hooks' +import { useAccount } from 'hooks/useAccount' import { getChainIdFromSlug } from 'utils/string' import { useChangeNetwork } from './useChangeNetwork' @@ -16,30 +17,46 @@ export function useSyncNetworkParamWithStore() { const location = useLocation() const [requestingNetwork, setRequestingNetwork] = useState() const triedSync = useRef(false) + const chainIdKeeper = useRef(0) + const networkParamKeeper = useRef('') + const { connector, isConnected } = useAccount() useEffect(() => { if (!networkParam || !paramChainId || isWrongNetwork) { triedSync.current = true return } + if (!chainIdKeeper.current) chainIdKeeper.current = paramChainId + if (!networkParamKeeper.current) + networkParamKeeper.current = networkParam - /** - * Try to change to network on route param on init. Exp: /swap/ethereum => try to connect to ethereum on init - * @param isOnInit.current: make sure only run 1 time after init - * @param triedEager: only run after tried to connect injected wallet - */ + /** + * Try to change to network on route param on init. Exp: /swap/ethereum => try to connect to ethereum on init + * @param isOnInit.current: make sure only run 1 time after init + * @param triedEager: only run after tried to connect injected wallet + */ ;(async () => { - if (triedSync.current) return - setRequestingNetwork(networkParam) - await changeNetwork(paramChainId, undefined, () => { + if (triedSync.current || (isConnected && !connector?.switchChain)) return + setRequestingNetwork(networkParamKeeper.current) + await changeNetwork(chainIdKeeper.current, undefined, () => { navigate( - { ...location, pathname: location.pathname.replace(networkParam, networkInfo.route) }, + { ...location, pathname: location.pathname.replace(networkParamKeeper.current, networkInfo.route) }, { replace: true }, ) }) triedSync.current = true })() - }, [changeNetwork, location, navigate, networkInfo.route, networkParam, paramChainId, isWrongNetwork]) + }, [ + changeNetwork, + location, + navigate, + networkInfo.route, + networkParam, + paramChainId, + isWrongNetwork, + connector?.switchChain, + isConnected, + ]) useEffect(() => { if (NETWORKS_INFO[chainId].route === requestingNetwork) setRequestingNetwork(undefined)