initial commit
This commit is contained in:
59
src/hooks/useLatestSighting.ts
Normal file
59
src/hooks/useLatestSighting.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
|
||||
async function fetchSighting() {
|
||||
const response = await fetch(
|
||||
`http://100.116.253.81/mergedHistory/sightingSummary?mostRecentRef=-1`
|
||||
);
|
||||
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: 500,
|
||||
});
|
||||
|
||||
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 };
|
||||
}
|
||||
Reference in New Issue
Block a user