Files
Mav-Mobile-UI/src/hooks/useLatestSighting.ts

61 lines
1.6 KiB
TypeScript
Raw Normal View History

2025-08-13 14:23:48 +01:00
import { useQuery } from "@tanstack/react-query";
import { useCallback, useEffect, useRef } from "react";
async function fetchSighting() {
const response = await fetch(
2025-08-29 14:55:37 +01:00
// `http://100.82.205.44/api`
`http://192.168.75.11/mergedHistory/sightingSummary?mostRecentRef=-1`
2025-08-13 14:23:48 +01:00
);
if (!response.ok) throw new Error("Failed to fetch sighting");
return response.json();
}
export function useLatestSighting() {
const latestUrlRef = useRef<string | null>(null);
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const sightingImageRef = useRef<HTMLImageElement | null>(null);
const drawImage = useCallback(() => {
const canvas = canvasRef.current;
const ctx = canvas?.getContext("2d");
const img2 = sightingImageRef.current;
if (!img2 || !canvas) return;
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
ctx?.drawImage(img2, 0, 0, 200, 50);
}, [sightingImageRef]);
const { data } = useQuery({
queryKey: ["latestSighting"],
queryFn: fetchSighting,
refetchInterval: 100,
2025-08-13 14:23:48 +01:00
});
useEffect(() => {
const img = new Image();
sightingImageRef.current = img;
img.onload = () => {
drawImage();
};
img.src = data?.plateUrlColour;
if (latestUrlRef.current) {
URL.revokeObjectURL(latestUrlRef.current);
}
latestUrlRef.current = img.src;
return () => {
if (latestUrlRef.current) {
URL.revokeObjectURL(latestUrlRef.current);
latestUrlRef.current = null;
}
};
}, [data?.plateUrlColour, drawImage]);
return { data, sightingImageRef, canvasRef };
}