49 lines
1.3 KiB
TypeScript
49 lines
1.3 KiB
TypeScript
import { useEffect } from 'react'
|
|
import { connectorLocalStorageKey, ConnectorNames } from '@pancakeswap/uikit'
|
|
import useAuth from 'hooks/useAuth'
|
|
import { useDispatch } from 'react-redux'
|
|
import { clearUserInfo } from 'state/actions'
|
|
|
|
const _binanceChainListener = async () =>
|
|
new Promise<void>((resolve) =>
|
|
Object.defineProperty(window, 'BinanceChain', {
|
|
get() {
|
|
return this.bsc
|
|
},
|
|
set(bsc) {
|
|
this.bsc = bsc
|
|
|
|
resolve()
|
|
},
|
|
}),
|
|
)
|
|
|
|
const useEagerConnect = () => {
|
|
const { login } = useAuth()
|
|
const dispatch = useDispatch()
|
|
|
|
useEffect(() => {
|
|
const connectorId = window.localStorage.getItem(connectorLocalStorageKey) as ConnectorNames
|
|
|
|
if (connectorId) {
|
|
const isConnectorBinanceChain = connectorId === ConnectorNames.BSC
|
|
const isBinanceChainDefined = Reflect.has(window, 'BinanceChain')
|
|
|
|
// Currently BSC extension doesn't always inject in time.
|
|
// We must check to see if it exists, and if not, wait for it before proceeding.
|
|
if (isConnectorBinanceChain && !isBinanceChainDefined) {
|
|
_binanceChainListener().then(() => login(connectorId))
|
|
|
|
return
|
|
}
|
|
|
|
login(connectorId)
|
|
} else {
|
|
// 要清掉用户信息
|
|
dispatch(clearUserInfo())
|
|
}
|
|
}, [login, dispatch])
|
|
}
|
|
|
|
export default useEagerConnect
|