A typed utility that wraps the Fetch API with error handling and JSON parsing, returning a structured result or error object.
1async function fetchJSON<T>(
2 url: string
3): Promise<{ data: T | null; error: string | null }> {
4 try {
5 const res = await fetch(url);
6 if (!res.ok) throw new Error(`HTTP ${res.status}`);
7 const data: T = await res.json();
8 return { data, error: null };
9 } catch (err) {
10 return { data: null, error: (err as Error).message };
11 }
12}