mirror of
https://github.com/luxfi/explore.git
synced 2026-09-24 00:28:18 +00:00
* Support both chain slug and chain id in page parameters in multichain explorer mode Resolves #3320 * fix test
75 lines
1.9 KiB
TypeScript
75 lines
1.9 KiB
TypeScript
import { useRouter } from 'next/router';
|
|
import React from 'react';
|
|
|
|
import type { ClusterChainConfig } from 'types/multichain';
|
|
|
|
import multichainConfig from 'configs/multichain';
|
|
import getChainIdFromSlugOrId from 'lib/multichain/getChainIdFromSlugOrId';
|
|
import getQueryParamString from 'lib/router/getQueryParamString';
|
|
|
|
interface MultichainProviderProps {
|
|
children: React.ReactNode;
|
|
chainId?: string;
|
|
}
|
|
|
|
export interface TMultichainContext {
|
|
chain: ClusterChainConfig;
|
|
}
|
|
|
|
export const MultichainContext = React.createContext<TMultichainContext | null>(null);
|
|
|
|
export function MultichainProvider({ children, chainId: chainIdProp }: MultichainProviderProps) {
|
|
const router = useRouter();
|
|
const chainSlugOrIdQueryParam = router.pathname.includes('chain_slug_or_id') ? getQueryParamString(router.query.chain_slug_or_id) : undefined;
|
|
const chainIdQueryParam = router.query.chain_id ? getQueryParamString(router.query.chain_id) : undefined;
|
|
|
|
const [ chainId, setChainId ] = React.useState<string | undefined>(
|
|
chainIdProp ??
|
|
chainIdQueryParam ??
|
|
(chainSlugOrIdQueryParam ? getChainIdFromSlugOrId(chainSlugOrIdQueryParam) : undefined),
|
|
);
|
|
|
|
React.useEffect(() => {
|
|
if (chainIdProp) {
|
|
setChainId(chainIdProp);
|
|
}
|
|
}, [ chainIdProp ]);
|
|
|
|
const chain = React.useMemo(() => {
|
|
const config = multichainConfig();
|
|
if (!config) {
|
|
return;
|
|
}
|
|
|
|
if (!chainId) {
|
|
return;
|
|
}
|
|
|
|
return config.chains.find((chain) => chain.id === chainId);
|
|
}, [ chainId ]);
|
|
|
|
const value = React.useMemo(() => {
|
|
if (!chain) {
|
|
return null;
|
|
}
|
|
|
|
return {
|
|
chain,
|
|
};
|
|
}, [ chain ]);
|
|
|
|
return (
|
|
<MultichainContext.Provider value={ value }>
|
|
{ children }
|
|
</MultichainContext.Provider>
|
|
);
|
|
}
|
|
|
|
export function useMultichainContext(disabled: boolean = !multichainConfig) {
|
|
const context = React.useContext(MultichainContext);
|
|
if (context === undefined || disabled) {
|
|
return null;
|
|
}
|
|
return context;
|
|
}
|