From 027e7424d3dbc18c64221ff48095f719caf53e7a Mon Sep 17 00:00:00 2001 From: Tien Nguyen Date: Tue, 29 Oct 2024 16:31:57 +0700 Subject: [PATCH] fix bug switch chain in wagmi on app open --- .../web3/useSyncNetworkParamWithStore.ts | 37 +++++++++++++------ 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/src/hooks/web3/useSyncNetworkParamWithStore.ts b/src/hooks/web3/useSyncNetworkParamWithStore.ts index 19d8d9eebe..1a4ca9a750 100644 --- a/src/hooks/web3/useSyncNetworkParamWithStore.ts +++ b/src/hooks/web3/useSyncNetworkParamWithStore.ts @@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react' import { useLocation, useNavigate, useParams } from 'react-router-dom' import { NETWORKS_INFO } from 'constants/networks' -import { useActiveWeb3React } from 'hooks' +import { useActiveWeb3React, useWeb3React } from 'hooks' import { getChainIdFromSlug } from 'utils/string' import { useChangeNetwork } from './useChangeNetwork' @@ -16,30 +16,45 @@ export function useSyncNetworkParamWithStore() { const location = useLocation() const [requestingNetwork, setRequestingNetwork] = useState() const triedSync = useRef(false) + const chainIdKeeper = useRef(0) + const networkParamKeeper = useRef('') + const { connector } = useWeb3React() 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 || !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, + ]) useEffect(() => { if (NETWORKS_INFO[chainId].route === requestingNetwork) setRequestingNetwork(undefined)