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 { Light as SyntaxHighlighter } from "react-syntax-highlighter";
import hljs from "highlight.js"; import hljs from "highlight.js";
import docco from "react-syntax-highlighter/dist/esm/styles/hljs/docco"; import docco from "react-syntax-highlighter/dist/esm/styles/hljs/docco";
import { sourcifySourceFile } from "../url";
import hljsDefineSolidity from "highlightjs-solidity"; import hljsDefineSolidity from "highlightjs-solidity";
import { useContract } from "../useSourcify";
hljsDefineSolidity(hljs); hljsDefineSolidity(hljs);
type ContractProps = { type ContractProps = {
@ -21,27 +20,7 @@ const Contract: React.FC<ContractProps> = ({
filename, filename,
source, source,
}) => { }) => {
const [content, setContent] = useState<string>(source.content); const content = useContract(checksummedAddress, networkId, filename, source);
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 ( return (
<SyntaxHighlighter <SyntaxHighlighter

View File

@ -1,5 +1,5 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { sourcifyMetadata } from "./url"; import { sourcifyMetadata, sourcifySourceFile } from "./url";
export type Metadata = { export type Metadata = {
version: string; version: string;
@ -70,3 +70,35 @@ export const useSourcify = (
return rawMetadata; 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;
};