Fix fetch cancellation

This commit is contained in:
Willian Mitsuda 2021-09-13 22:24:22 -03:00
parent ac543caf7f
commit d5e9f303a1
1 changed files with 15 additions and 3 deletions

View File

@ -47,8 +47,9 @@ export const useSourcify = (
if (!checksummedAddress || chainId === undefined) { if (!checksummedAddress || chainId === undefined) {
return; return;
} }
setRawMetadata(undefined); setRawMetadata(undefined);
const abortController = new AbortController();
const fetchMetadata = async () => { const fetchMetadata = async () => {
try { try {
const contractMetadataURL = sourcifyMetadata( const contractMetadataURL = sourcifyMetadata(
@ -56,7 +57,9 @@ export const useSourcify = (
chainId, chainId,
source source
); );
const result = await fetch(contractMetadataURL); const result = await fetch(contractMetadataURL, {
signal: abortController.signal,
});
if (result.ok) { if (result.ok) {
const _metadata = await result.json(); const _metadata = await result.json();
setRawMetadata(_metadata); setRawMetadata(_metadata);
@ -69,6 +72,10 @@ export const useSourcify = (
} }
}; };
fetchMetadata(); fetchMetadata();
return () => {
abortController.abort();
};
}, [checksummedAddress, chainId, source]); }, [checksummedAddress, chainId, source]);
return rawMetadata; return rawMetadata;
@ -88,6 +95,7 @@ export const useContract = (
return; return;
} }
const abortController = new AbortController();
const readContent = async () => { const readContent = async () => {
const normalizedFilename = filename.replaceAll(/[@:]/g, "_"); const normalizedFilename = filename.replaceAll(/[@:]/g, "_");
const url = sourcifySourceFile( const url = sourcifySourceFile(
@ -96,13 +104,17 @@ export const useContract = (
normalizedFilename, normalizedFilename,
sourcifySource sourcifySource
); );
const res = await fetch(url); const res = await fetch(url, { signal: abortController.signal });
if (res.ok) { if (res.ok) {
const _content = await res.text(); const _content = await res.text();
setContent(_content); setContent(_content);
} }
}; };
readContent(); readContent();
return () => {
abortController.abort();
};
}, [checksummedAddress, networkId, filename, source.content, sourcifySource]); }, [checksummedAddress, networkId, filename, source.content, sourcifySource]);
return content; return content;