import { useState, useEffect, useCallback } from 'react'; interface UseApiOptions { autoFetch?: boolean; } interface UseApiResult { data: T | null; loading: boolean; error: string | null; refetch: () => Promise; } export function useApi( url: string, options: UseApiOptions = { autoFetch: true } ): UseApiResult { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const fetchData = useCallback(async () => { setLoading(true); setError(null); try { const response = await fetch(url); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.error || 'Failed to fetch data'); } const result = await response.json(); setData(result); } catch (err) { setError(err instanceof Error ? err.message : 'An error occurred'); } finally { setLoading(false); } }, [url]); useEffect(() => { if (options.autoFetch) { fetchData(); } }, [fetchData, options.autoFetch]); return { data, loading, error, refetch: fetchData }; } export async function apiCall( url: string, options?: RequestInit ): Promise { const response = await fetch(url, options); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.error || 'API call failed'); } return response.json(); }