import { useEffect, useState } from "react"; // En dev el proxy de Vite manda /api al backend; en producción la propia API // sirve el build, así que la ruta relativa funciona en ambos casos. const BASE = ""; export type Filtros = { tipo?: string; sexo?: string; departamento?: string; lugar?: string; desde?: string; hasta?: string; }; export type Meta = { anio_min: string; anio_max: string; filas: number; fecha_max: string; ultimo_mes: string; anios: string[]; tipos_muerte: string[]; sexos: string[]; lugares: string[]; departamentos: string[]; actualizado: number; verificado: string | null; }; export function qs(f: Filtros, extra: Record = {}) { const p = new URLSearchParams(); for (const [k, v] of Object.entries({ ...f, ...extra })) { if (v) p.set(k, v); } return p.toString(); } async function get(path: string): Promise { const r = await fetch(`${BASE}${path}`); if (!r.ok) throw new Error(`${r.status} ${await r.text()}`); return r.json(); } /** Fetch con estado. La key evita aplicar respuestas de peticiones obsoletas. */ export function useApi(path: string | null): { data: T | null; error: string | null } { const [data, setData] = useState(null); const [error, setError] = useState(null); useEffect(() => { if (!path) return; let vigente = true; setError(null); get(path) .then((d) => vigente && setData(d)) .catch((e) => vigente && setError(String(e))); return () => { vigente = false; }; }, [path]); return { data, error }; }