This code violates DRY by duplicating the fetch logic, error handling, and response processing across components. A better approach would be to create a reusable API client:
const apiClient = {
async fetch(endpoint, options = {}) {
try {
const response = await fetch(`/api/${endpoint}`, options);
if (!response.ok) throw new Error(`Failed to fetch ${endpoint}`);
return await response.json();
} catch (error) {
console.error(`Error fetching ${endpoint}:`, error);
throw error;
}
}
};
// Usage in components:
const user = await apiClient.fetch(`users/${id}`);
const product = await apiClient.fetch(`products/${id}`);