Fetch chainInfo using SWR

This commit is contained in:
Willian Mitsuda 2022-08-22 16:05:37 -03:00
parent 4fcf886808
commit d0f68000be
No known key found for this signature in database

View File

@ -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;
} }
return data;
const readChainInfo = async () => {
try {
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 => {