Skip to content

Commit 1c3f30e

Browse files
atsai-jumptradingjherrera-jump
authored andcommitted
Fix: rate hook sometimes resulting in negative values
1 parent d9893c5 commit 1c3f30e

File tree

1 file changed

+11
-13
lines changed

1 file changed

+11
-13
lines changed

src/features/StartupProgress/Firedancer/useValuePerSecond.ts

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,9 @@ import { useInterval } from "react-use";
88
function addNewValueAndShift(
99
prev: [number, number][],
1010
newValue: number,
11-
now: number,
1211
windowMs: number,
1312
) {
13+
const now = performance.now();
1414
const newValues = [...prev, [newValue, now]] satisfies [number, number][];
1515

1616
while (
@@ -33,23 +33,21 @@ export function useValuePerSecond(
3333

3434
useEffect(() => {
3535
if (cumulativeValue == null) return;
36-
37-
const now = performance.now();
38-
setValues((prev) =>
39-
addNewValueAndShift(prev, cumulativeValue, now, windowMs),
40-
);
36+
setValues((prev) => addNewValueAndShift(prev, cumulativeValue, windowMs));
4137
}, [cumulativeValue, windowMs]);
4238

4339
// Handle unchanged cumulative values by
4440
// adding the unchanged value to the end of the array
4541
useInterval(() => {
46-
const now = performance.now();
47-
const latestValue = values[values.length - 1];
48-
if (latestValue && latestValue[1] < now - windowMs) {
49-
setValues((prev) =>
50-
addNewValueAndShift(prev, latestValue[0], now, windowMs),
51-
);
52-
}
42+
setValues((prev) => {
43+
const now = performance.now();
44+
const latestValue = prev[prev.length - 1];
45+
if (latestValue && latestValue[1] < now - windowMs) {
46+
return addNewValueAndShift(prev, prev[prev.length - 1][0], windowMs);
47+
} else {
48+
return prev;
49+
}
50+
});
5351
}, windowMs);
5452

5553
const reset = useCallback(() => {

0 commit comments

Comments
 (0)