forked from Uniswap/interface
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseSyncChainQuery.ts
More file actions
53 lines (42 loc) · 1.81 KB
/
Copy pathuseSyncChainQuery.ts
File metadata and controls
53 lines (42 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { useWeb3React } from '@web3-react/core'
import { CHAIN_IDS_TO_NAMES } from 'constants/chains'
import { ParsedQs } from 'qs'
import { useEffect, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import useParsedQueryString from './useParsedQueryString'
import usePrevious from './usePrevious'
import useSelectChain from './useSelectChain'
function getChainIdFromName(name: string) {
const entry = Object.entries(CHAIN_IDS_TO_NAMES).find(([_, n]) => n === name)
const chainId = entry?.[0]
return chainId ? parseInt(chainId) : undefined
}
function getParsedChainId(parsedQs?: ParsedQs) {
const chain = parsedQs?.chain
if (!chain || typeof chain !== 'string') return
return getChainIdFromName(chain)
}
export default function useSyncChainQuery() {
const { chainId, isActive } = useWeb3React()
const parsedQs = useParsedQueryString()
const urlChainId = getParsedChainId(parsedQs)
const previousUrlChainId = usePrevious(urlChainId)
const selectChain = useSelectChain()
// Can't use `usePrevious` because `chainId` can be undefined while activating.
const [previousChainId, setPreviousChainId] = useState<number | undefined>(undefined)
useEffect(() => {
if (chainId && chainId !== previousChainId) {
setPreviousChainId(chainId)
}
}, [chainId, previousChainId])
const [searchParams, setSearchParams] = useSearchParams()
const chainQueryManuallyUpdated = urlChainId && urlChainId !== previousUrlChainId && isActive
return useEffect(() => {
if (chainQueryManuallyUpdated) {
// If the query param changed, and the chain didn't change, then activate the new chain
selectChain(urlChainId)
searchParams.delete('chain')
setSearchParams(searchParams)
}
}, [chainQueryManuallyUpdated, urlChainId, selectChain, searchParams, setSearchParams])
}