Skip to content

Commit

Permalink
perf(utils): avoid fetching the same URL multiple times
Browse files Browse the repository at this point in the history
  • Loading branch information
yomatters committed Dec 13, 2024
1 parent 8a56d0c commit 0e2b050
Showing 1 changed file with 27 additions and 27 deletions.
54 changes: 27 additions & 27 deletions src/utils.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,32 @@ export const getScrollTop = () =>
: (document.documentElement || document.body.parentNode || document.body)
.scrollTop;

const jsonCache = {};
const fetchJsonDataCache = {};
const fetchJsonPromiseCache = {};
const fetchJson = (
uri,
{ cache = true, corsProxy = false } = { cache: true, corsProxy: false }
) => {
if (cache && uri in fetchJsonDataCache) return fetchJsonDataCache[uri];
if (uri in fetchJsonPromiseCache) return fetchJsonPromiseCache[uri];
const promise = fetch(
corsProxy ? `https://corsproxy.io/?${encodeURIComponent(uri)}` : uri
).then((response) => {
delete fetchJsonPromiseCache[uri];
if (response.status < 200 || response.status > 299) {
return { error: { status: response.status } };
} else {
try {
return response.json();
} catch (error) {
return { error: { message: error } };
}
}
});
fetchJsonPromiseCache[uri] = promise;
return promise;
};

export const useJSON = (
uris,
{ cache = true, corsProxy = false, defaultValue = null } = {
Expand All @@ -40,37 +65,12 @@ export const useJSON = (
}
useEffect(() => {
if (uris.length) {
const cacheKey = uris.join(" ");
if (cache && jsonCache[cacheKey]) {
setValue(jsonCache[cacheKey]);
return;
}
(async () => {
const responses = await Promise.all(
uris.map((uri) =>
fetch(
corsProxy
? `https://corsproxy.io/?${encodeURIComponent(uri)}`
: uri
)
)
);
const json = await Promise.all(
responses.map((response) => {
if (response.status < 200 || response.status > 299) {
return { error: { status: response.status } };
} else {
try {
return response.json();
} catch (error) {
return { error: { message: error } };
}
}
})
uris.map((uri) => fetchJson(uri, { cache, corsProxy }))
);
const result = single ? json[0] : json;
setValue(result);
if (cache) jsonCache[cacheKey] = result;
})();
}
}, [...uris]);
Expand Down

0 comments on commit 0e2b050

Please sign in to comment.