Fetch chainInfo using SWR
This commit is contained in:
parent
4fcf886808
commit
d0f68000be
@ -1,4 +1,5 @@
|
|||||||
import { createContext, useContext, useEffect, useState } from "react";
|
import { createContext, useContext } from "react";
|
||||||
|
import useSWRImmutable from "swr/immutable";
|
||||||
import { chainInfoURL } from "./url";
|
import { chainInfoURL } from "./url";
|
||||||
import { OtterscanRuntime } from "./useRuntime";
|
import { OtterscanRuntime } from "./useRuntime";
|
||||||
|
|
||||||
@ -24,40 +25,33 @@ export const defaultChainInfo: ChainInfo = {
|
|||||||
|
|
||||||
export const ChainInfoContext = createContext<ChainInfo | undefined>(undefined);
|
export const ChainInfoContext = createContext<ChainInfo | undefined>(undefined);
|
||||||
|
|
||||||
|
const chainInfoFetcher = async (assetsURLPrefix: string, chainId: number) => {
|
||||||
|
const url = chainInfoURL(assetsURLPrefix, chainId);
|
||||||
|
const res = await fetch(url);
|
||||||
|
if (!res.ok) {
|
||||||
|
return defaultChainInfo;
|
||||||
|
}
|
||||||
|
|
||||||
|
const info: ChainInfo = await res.json();
|
||||||
|
return info;
|
||||||
|
};
|
||||||
|
|
||||||
export const useChainInfoFromMetadataFile = (
|
export const useChainInfoFromMetadataFile = (
|
||||||
runtime: OtterscanRuntime | undefined
|
runtime: OtterscanRuntime | undefined
|
||||||
): ChainInfo | undefined => {
|
): ChainInfo | undefined => {
|
||||||
const assetsURLPrefix = runtime?.config?.assetsURLPrefix;
|
const assetsURLPrefix = runtime?.config?.assetsURLPrefix;
|
||||||
const chainId = runtime?.provider?.network.chainId;
|
const chainId = runtime?.provider?.network.chainId;
|
||||||
|
|
||||||
const [chainInfo, setChainInfo] = useState<ChainInfo | undefined>(undefined);
|
const { data, error } = useSWRImmutable(
|
||||||
|
assetsURLPrefix !== undefined && chainId !== undefined
|
||||||
useEffect(() => {
|
? [assetsURLPrefix, chainId]
|
||||||
if (assetsURLPrefix === undefined || chainId === undefined) {
|
: null,
|
||||||
setChainInfo(undefined);
|
chainInfoFetcher
|
||||||
return;
|
);
|
||||||
}
|
if (error) {
|
||||||
|
return defaultChainInfo;
|
||||||
const readChainInfo = async () => {
|
}
|
||||||
try {
|
return data;
|
||||||
const res = await fetch(chainInfoURL(assetsURLPrefix, chainId));
|
|
||||||
if (!res.ok) {
|
|
||||||
setChainInfo(defaultChainInfo);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const info: ChainInfo = await res.json();
|
|
||||||
setChainInfo(info);
|
|
||||||
} catch (err) {
|
|
||||||
// ignore
|
|
||||||
setChainInfo(defaultChainInfo);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
readChainInfo();
|
|
||||||
}, [assetsURLPrefix, chainId]);
|
|
||||||
|
|
||||||
return chainInfo;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const useChainInfo = (): ChainInfo => {
|
export const useChainInfo = (): ChainInfo => {
|
||||||
|
Loading…
Reference in New Issue
Block a user