Skip to content

Commit 768921c

Browse files
committed
Add cache for the same fetch urls.
1 parent 3268870 commit 768921c

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

src/utils/dataLoader.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
const dataCache: Record<string, any> = {};
2+
13
export async function loadData(
24
apiUrl: string,
35
maxRetries = 3,
@@ -7,6 +9,11 @@ export async function loadData(
79
throw new Error(`No API URL provided`);
810
}
911

12+
if (dataCache[apiUrl]) {
13+
console.log(`Cache hit for: ${apiUrl}`);
14+
return dataCache[apiUrl];
15+
}
16+
1017
for (let attempt = 1; attempt <= maxRetries; attempt++) {
1118
try {
1219
console.log(`Fetching data from: ${apiUrl} (Attempt ${attempt})`);
@@ -35,10 +42,9 @@ export async function loadData(
3542
console.log(
3643
`Received JSON object with ${Object.keys(data).length} keys`
3744
);
38-
} else {
39-
console.log(`Received JSON of type: ${typeof data}`);
4045
}
4146

47+
dataCache[apiUrl] = data;
4248
return data;
4349
} catch (error) {
4450
console.error(`Attempt ${attempt} failed:`, error);

0 commit comments

Comments
 (0)