Skip to content
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 40 additions & 15 deletions src/utils/dataLoader.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,47 @@
export async function loadData(apiUrl: any) {
export async function loadData(
apiUrl: string,
maxRetries = 3,
retryDelay = 1000
): Promise<any> {
if (!apiUrl) {
console.warn(`No API URL provided`);
return {};
throw new Error(`No API URL provided`);
}

try {
console.log(`Fetching data from: ${apiUrl}`);
const response = await fetch(apiUrl);
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
console.log(`Fetching data from: ${apiUrl} (Attempt ${attempt})`);
const response = await fetch(apiUrl);

if (!response.ok) {
throw new Error(
`Failed to fetch data: ${response.status} ${response.statusText}`
);
}
if (!response.ok) {
throw new Error(
`Fetch failed: ${response.status} ${response.statusText}`
);
}

const data = await response.json();

if (
data == null ||
(typeof data === "object" &&
!Array.isArray(data) &&
Object.keys(data).length === 0)
) {
throw new Error(`Received empty or invalid JSON`);
}

return await response.json();
} catch (error) {
console.error(`Error loading data:`, error);
return {};
return data;
} catch (error) {
console.error(`Attempt ${attempt} failed:`, error);

if (attempt < maxRetries) {
await new Promise((res) => setTimeout(res, retryDelay));
} else {
throw new Error(
`Failed to load data from ${apiUrl} after ${maxRetries} attempts`
);
}
}
}

throw new Error(`Unexpected execution path`);
}