Skip to content

Commit 372db2b

Browse files
committed
Fix Recharts NaN crash by gracefully mapping string to number
1 parent 5921e35 commit 372db2b

1 file changed

Lines changed: 29 additions & 1 deletion

File tree

src/components/Content/History/Charts/StackedAreaChart.js

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,34 @@ const StackedAreaChart = ({ title, icon, color, prefix, names, baseColorHue = 0
3434
});
3535
}, [rawHistory, names, prefix]);
3636

37+
const chartData = useMemo(() => {
38+
return filteredData.map(d => {
39+
const safeData = { ...d };
40+
let visibleSum = 0;
41+
let firstVisibleKey = null;
42+
43+
visibleSeries.forEach(({ i }) => {
44+
const key = `${prefix}_${i}`;
45+
let val = Number(safeData[key]);
46+
if (isNaN(val) || val < 0) val = 0; // Prevent negative or invalid values
47+
48+
safeData[key] = val;
49+
50+
if (!hiddenSeries.has(key)) {
51+
visibleSum += val;
52+
if (!firstVisibleKey) firstVisibleKey = key;
53+
}
54+
});
55+
56+
// Prevent React/Recharts from crashing in Expand mode when total sum is exactly 0
57+
if (stackOffset === 'expand' && visibleSum === 0 && firstVisibleKey) {
58+
safeData[firstVisibleKey] = 0.000001;
59+
}
60+
61+
return safeData;
62+
});
63+
}, [filteredData, stackOffset, visibleSeries, hiddenSeries, prefix]);
64+
3765
const getClosestSeries = (e) => {
3866
if (!e || !e.activePayload || e.activePayload.length === 0) return null;
3967
// For stacked charts, finding "closest" is tricky because they stack.
@@ -132,7 +160,7 @@ const StackedAreaChart = ({ title, icon, color, prefix, names, baseColorHue = 0
132160
<Box sx={{ px: 1 }}>
133161
<ResponsiveContainer width="100%" height={380}>
134162
<AreaChart
135-
data={filteredData}
163+
data={chartData}
136164
margin={{ top: 10, right: 30, left: 10, bottom: 0 }}
137165
stackOffset={stackOffset}
138166
>

0 commit comments

Comments
 (0)