parent
7340ea589a
commit
820f6cbb28
@ -0,0 +1,48 @@ |
||||
import { useRouter } from 'next/router'; |
||||
import { useEffect } from 'react'; |
||||
|
||||
import { Environment, envDisplayValue, environments } from '../../consts/environments'; |
||||
import { useEnvironment } from '../../store'; |
||||
import { getQueryParamString, replacePathParam } from '../../utils/queryParams'; |
||||
import { SelectField } from '../input/SelectField'; |
||||
|
||||
export function EnvironmentSelector() { |
||||
const router = useRouter(); |
||||
const { environment, setEnvironment } = useEnvironment(); |
||||
|
||||
const queryEnv = getQueryParamString(router.query, 'env'); |
||||
useEffect(() => { |
||||
if (!queryEnv || queryEnv === environment) return; |
||||
if (environments.includes(queryEnv as Environment)) { |
||||
setEnvironment(queryEnv as Environment); |
||||
} |
||||
// special case to alias testnet as testnet2
|
||||
if (queryEnv.toLowerCase() === 'testnet') { |
||||
setEnvironment(Environment.Testnet2); |
||||
} |
||||
// Only run once on mount
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []); |
||||
|
||||
const onSelect = (env: string) => { |
||||
setEnvironment(env as Environment); |
||||
replacePathParam('env', env); |
||||
}; |
||||
|
||||
return ( |
||||
<div className="relative"> |
||||
{/* <Image src={HubIcon} width={20} height={20} className="opacity-70" /> */} |
||||
<SelectField |
||||
classes="w-24 text-gray-600 border-gray-600 bg-gray-50 text-[0.95rem]" |
||||
options={envOptions} |
||||
value={environment} |
||||
onValueSelect={onSelect} |
||||
/> |
||||
</div> |
||||
); |
||||
} |
||||
|
||||
const envOptions = [ |
||||
{ value: Environment.Mainnet, display: envDisplayValue[Environment.Mainnet] }, |
||||
{ value: Environment.Testnet2, display: envDisplayValue[Environment.Testnet2] }, |
||||
]; |
@ -0,0 +1,28 @@ |
||||
import type { ParsedUrlQuery } from 'querystring'; |
||||
|
||||
import { logger } from './logger'; |
||||
|
||||
// To make Next's awkward query param typing more convenient
|
||||
export function getQueryParamString(query: ParsedUrlQuery, key: string, defaultVal = '') { |
||||
if (!query) return defaultVal; |
||||
const val = query[key]; |
||||
if (val && typeof val === 'string') return val; |
||||
else return defaultVal; |
||||
} |
||||
|
||||
// Circumventing Next's router.replace method here because
|
||||
// it's async and causes race conditions btwn components.
|
||||
// This will only modify the url but not trigger any routing
|
||||
export function replacePathParam(key: string, val: string) { |
||||
try { |
||||
const url = new URL(window.location.href); |
||||
if (val) { |
||||
url.searchParams.set(key, val); |
||||
} else { |
||||
url.searchParams.delete(key); |
||||
} |
||||
window.history.replaceState('', '', url); |
||||
} catch (error) { |
||||
logger.error('Error replacing path param', error); |
||||
} |
||||
} |
Loading…
Reference in new issue