Extract hook

This commit is contained in:
Willian Mitsuda 2021-09-06 02:09:12 -03:00
parent 71e359eb92
commit dfcbc1a150
2 changed files with 36 additions and 25 deletions

View File

@ -1,11 +1,10 @@
import React, { useState, useEffect } from "react";
import React from "react";
import { Light as SyntaxHighlighter } from "react-syntax-highlighter";
import hljs from "highlight.js";
import docco from "react-syntax-highlighter/dist/esm/styles/hljs/docco";
import { sourcifySourceFile } from "../url";
import hljsDefineSolidity from "highlightjs-solidity";
import { useContract } from "../useSourcify";
hljsDefineSolidity(hljs);
type ContractProps = {
@ -21,27 +20,7 @@ const Contract: React.FC<ContractProps> = ({
filename,
source,
}) => {
const [content, setContent] = useState<string>(source.content);
useEffect(() => {
if (source.content) {
return;
}
const readContent = async () => {
const normalizedFilename = filename.replaceAll("@", "_");
const url = sourcifySourceFile(
checksummedAddress,
networkId,
normalizedFilename
);
const res = await fetch(url);
if (res.ok) {
const _content = await res.text();
setContent(_content);
}
};
readContent();
}, [checksummedAddress, networkId, filename, source.content]);
const content = useContract(checksummedAddress, networkId, filename, source);
return (
<SyntaxHighlighter

View File

@ -1,5 +1,5 @@
import { useState, useEffect } from "react";
import { sourcifyMetadata } from "./url";
import { sourcifyMetadata, sourcifySourceFile } from "./url";
export type Metadata = {
version: string;
@ -70,3 +70,35 @@ export const useSourcify = (
return rawMetadata;
};
export const useContract = (
checksummedAddress: string,
networkId: number,
filename: string,
source: any
) => {
const [content, setContent] = useState<string>(source.content);
useEffect(() => {
if (source.content) {
return;
}
const readContent = async () => {
const normalizedFilename = filename.replaceAll("@", "_");
const url = sourcifySourceFile(
checksummedAddress,
networkId,
normalizedFilename
);
const res = await fetch(url);
if (res.ok) {
const _content = await res.text();
setContent(_content);
}
};
readContent();
}, [checksummedAddress, networkId, filename, source.content]);
return content;
};