import { useQuery } from "@tanstack/react-query"; import { useCallback, useEffect, useRef } from "react"; async function fetchSighting() { const response = await fetch( // `http://100.82.205.44/api` `http://192.168.75.11/mergedHistory/sightingSummary?mostRecentRef=-1` ); if (!response.ok) throw new Error("Failed to fetch sighting"); return response.json(); } export function useLatestSighting() { const latestUrlRef = useRef(null); const canvasRef = useRef(null); const sightingImageRef = useRef(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, }); 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 }; }