Skip to content

Commit 5c50bc4

Browse files
Merge pull request #115 from NessieCanCode/fix-data-duplication-in-charts
Fix billing data refresh loops
2 parents d0ffb89 + e63e94d commit 5c50bc4

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

src/slurmcostmanager.js

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
const { useState, useEffect, useRef, useCallback } = React;
1+
const { useState, useEffect, useRef, useCallback, useMemo } = React;
22

33
// Determine the directory where the plugin's files are installed. When running
44
// inside Cockpit, `window.cockpit.manifest.path` points to the plugin root
@@ -50,8 +50,10 @@ function getYearPeriod(year = new Date().getFullYear()) {
5050
function useBillingData(period) {
5151
const [data, setData] = useState(null);
5252
const [error, setError] = useState(null);
53+
const requestIdRef = useRef(0);
5354

5455
const load = useCallback(async () => {
56+
const id = ++requestIdRef.current;
5557
try {
5658
let json;
5759
if (window.cockpit && window.cockpit.spawn) {
@@ -80,11 +82,15 @@ function useBillingData(period) {
8082
if (!resp.ok) throw new Error('Failed to fetch billing data');
8183
json = await resp.json();
8284
}
83-
setData(json);
84-
setError(null);
85+
if (requestIdRef.current === id) {
86+
setData(json);
87+
setError(null);
88+
}
8589
} catch (e) {
8690
console.error(e);
87-
setError(e.message || String(e));
91+
if (requestIdRef.current === id) {
92+
setError(e.message || String(e));
93+
}
8894
}
8995
}, [period]);
9096

@@ -1138,12 +1144,13 @@ function Rates({ onRatesUpdated }) {
11381144
function App() {
11391145
const [view, setView] = useState('year');
11401146
const now = new Date();
1141-
const defaultMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(
1147+
const currentYear = now.getFullYear();
1148+
const defaultMonth = `${currentYear}-${String(now.getMonth() + 1).padStart(
11421149
2,
11431150
'0'
11441151
)}`;
11451152
const [month, setMonth] = useState(defaultMonth);
1146-
const yearPeriod = getYearPeriod(now.getFullYear());
1153+
const yearPeriod = useMemo(() => getYearPeriod(currentYear), [currentYear]);
11471154
const period = view === 'year' ? yearPeriod : month;
11481155
const { data, error, reload } = useBillingData(period);
11491156
const [showErrorDetails, setShowErrorDetails] = useState(false);

0 commit comments

Comments
 (0)