wallet-connect-web-examples/dapps/react-dapp-v2/src/contexts/ChainDataContext.tsx

86 lines
1.8 KiB
TypeScript
Raw Normal View History

import { apiGetChainNamespace, ChainsMap } from "caip-api";
2022-08-08 09:32:24 +00:00
import {
createContext,
ReactNode,
useContext,
useEffect,
useState,
} from "react";
import { SolanaChainData } from "../chains/solana";
import { PolkadotChainData } from "../chains/polkadot";
import { ChainNamespaces, getAllChainNamespaces } from "../helpers";
/**
* Types
*/
interface IContext {
chainData: ChainNamespaces;
}
/**
* Context
*/
export const ChainDataContext = createContext<IContext>({} as IContext);
/**
* Provider
*/
2022-08-08 09:32:24 +00:00
export function ChainDataContextProvider({
children,
}: {
children: ReactNode | ReactNode[];
}) {
const [chainData, setChainData] = useState<ChainNamespaces>({});
const loadChainData = async () => {
const namespaces = getAllChainNamespaces();
const chainData: ChainNamespaces = {};
await Promise.all(
2022-08-08 09:32:24 +00:00
namespaces.map(async (namespace) => {
let chains: ChainsMap | undefined;
try {
if (namespace === "solana") {
chains = SolanaChainData;
} else if (namespace === "polkadot") {
chains = PolkadotChainData;
} else {
chains = await apiGetChainNamespace(namespace);
}
} catch (e) {
// ignore error
}
if (typeof chains !== "undefined") {
chainData[namespace] = chains;
}
2022-08-08 09:32:24 +00:00
})
);
setChainData(chainData);
};
useEffect(() => {
loadChainData();
}, []);
return (
<ChainDataContext.Provider
value={{
chainData,
}}
>
{children}
</ChainDataContext.Provider>
);
}
export function useChainData() {
const context = useContext(ChainDataContext);
if (context === undefined) {
2022-08-08 09:32:24 +00:00
throw new Error(
"useChainData must be used within a ChainDataContextProvider"
);
}
return context;
}