Use a ref instead of a state and clear timeout in AutoUpdatingCameraImage

This commit is contained in:
Josh Hawkins 2024-07-06 17:59:50 -05:00
parent 69879ae628
commit 5cd4720ef2
2 changed files with 18 additions and 15 deletions

View File

@ -1,4 +1,4 @@
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import CameraImage from "./CameraImage"; import CameraImage from "./CameraImage";
type AutoUpdatingCameraImageProps = { type AutoUpdatingCameraImageProps = {
@ -22,7 +22,7 @@ export default function AutoUpdatingCameraImage({
}: AutoUpdatingCameraImageProps) { }: AutoUpdatingCameraImageProps) {
const [key, setKey] = useState(Date.now()); const [key, setKey] = useState(Date.now());
const [fps, setFps] = useState<string>("0"); const [fps, setFps] = useState<string>("0");
const [timeoutId, setTimeoutId] = useState<NodeJS.Timeout>(); const timeoutRef = useRef<NodeJS.Timeout | null>(null);
useEffect(() => { useEffect(() => {
if (reloadInterval == -1) { if (reloadInterval == -1) {
@ -32,9 +32,9 @@ export default function AutoUpdatingCameraImage({
setKey(Date.now()); setKey(Date.now());
return () => { return () => {
if (timeoutId) { if (timeoutRef.current) {
clearTimeout(timeoutId); clearTimeout(timeoutRef.current);
setTimeoutId(undefined); timeoutRef.current = null;
} }
}; };
// we know that these deps are correct // we know that these deps are correct
@ -46,19 +46,21 @@ export default function AutoUpdatingCameraImage({
return; return;
} }
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
const loadTime = Date.now() - key; const loadTime = Date.now() - key;
if (showFps) { if (showFps) {
setFps((1000 / Math.max(loadTime, reloadInterval)).toFixed(1)); setFps((1000 / Math.max(loadTime, reloadInterval)).toFixed(1));
} }
setTimeoutId( timeoutRef.current = setTimeout(
setTimeout(
() => { () => {
setKey(Date.now()); setKey(Date.now());
}, },
loadTime > reloadInterval ? 1 : reloadInterval, loadTime > reloadInterval ? 1 : reloadInterval,
),
); );
// we know that these deps are correct // we know that these deps are correct
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps

View File

@ -256,9 +256,10 @@ export default function LivePlayer({
)} )}
<div <div
className={`absolute inset-0 w-full ${ className={cn(
showStillWithoutActivity && !liveReady ? "visible" : "invisible" "absolute inset-0 w-full",
}`} showStillWithoutActivity && !liveReady ? "visible" : "invisible",
)}
> >
<AutoUpdatingCameraImage <AutoUpdatingCameraImage
className="size-full" className="size-full"