import React, { useEffect, useState } from 'react'; interface KPI_TableProps { siteId: string; month: string; // format: "YYYY-MM" } interface MonthlyKPI { site: string; month: string; yield_kwh: number | null; consumption_kwh: number | null; grid_draw_kwh: number | null; efficiency: number | null; } const KPI_Table: React.FC = ({ siteId, month }) => { const [kpiData, setKpiData] = useState(null); const [loading, setLoading] = useState(false); useEffect(() => { const fetchKPI = async () => { setLoading(true); try { const res = await fetch(`http://localhost:8000/kpi/monthly?site=${siteId}&month=${month}`); const data = await res.json(); setKpiData(data); } catch (err) { console.error('Failed to fetch KPI:', err); setKpiData(null); // fallback } finally { setLoading(false); } }; if (siteId && month) fetchKPI(); }, [siteId, month]); if (!siteId) { return (

Monthly KPI

No site selected

); } if (loading) { return (

Monthly KPI

Loading...

); } // Use optional chaining and nullish coalescing to safely default values to 0 const yield_kwh = kpiData?.yield_kwh ?? 0; const consumption_kwh = kpiData?.consumption_kwh ?? 0; const grid_draw_kwh = kpiData?.grid_draw_kwh ?? 0; const efficiency = kpiData?.efficiency ?? 0; const data = [ { kpi: 'Monthly Yield', value: `${yield_kwh.toFixed(0)} kWh` }, { kpi: 'Monthly Consumption', value: `${consumption_kwh.toFixed(0)} kWh` }, { kpi: 'Monthly Grid Draw', value: `${grid_draw_kwh.toFixed(0)} kWh` }, { kpi: 'Efficiency', value: `${efficiency.toFixed(1)}%` }, ]; return (

Monthly KPI

{data.map((row) => ( ))}
KPI Value
{row.kpi} {row.value}
); }; export default KPI_Table;