import { useEffect, useMemo, useRef, useState } from "react"; import type { SightingWidgetType } from "../types/types"; import { useQuery } from "@tanstack/react-query"; // const url = `http://100.82.205.44/SightingListFront/sightingSummary?mostRecentRef=-1`; async function fetchSighting(url: string, ref: number, signal?: AbortSignal) { const dynamicUrl = `${url}${ref}`; const res = await fetch(dynamicUrl, { signal }); if (!res.ok) throw new Error(String(res.status)); return (await res.json()) as SightingWidgetType; } export function useSightingFeed(url: string) { const [sightings, setSightings] = useState( () => Array(7).fill(null) as unknown as SightingWidgetType[] ); const [noSighting, setNoSighting] = useState(false); const [selectedRef, setSelectedRef] = useState(null); const [mostRecent, setMostRecent] = useState(null); const mostRecentRef = useRef(-1); const lastSeenRef = useRef(null); const { data, isPending } = useQuery({ queryKey: ["sighting"], queryFn: ({ signal }) => fetchSighting(url, mostRecentRef.current, signal), refetchInterval: 200, refetchIntervalInBackground: true, refetchOnWindowFocus: false, staleTime: 0, notifyOnChangeProps: ["data"], }); useEffect(() => { if (!data) return; if (data.ref === -1) { setNoSighting(true); } else { setNoSighting(false); } if (data.ref === lastSeenRef.current) return; // duplicate payload → do nothing lastSeenRef.current = data.ref; setSightings((prev) => { const existing = prev.find((p) => p?.ref === data.ref); const next = existing ? prev : [data, ...prev.filter(Boolean)].slice(0, 7); const stillHasSelection = selectedRef != null && next.some((s) => s?.ref === selectedRef); if (!stillHasSelection) { setSelectedRef(data.ref); } return next; }); setMostRecent(sightings[0]); mostRecentRef.current = data.ref ?? -1; }, [data, selectedRef, sightings]); const selected = useMemo( () => selectedRef == null ? null : sightings.find((s) => s?.ref === selectedRef) ?? null, [sightings, selectedRef] ); const effectiveSelected = selected ?? mostRecent ?? null; return { sightings, selectedRef, setSelectedRef, mostRecent, effectiveSelected, mostRecentRef, isPending, noSighting, }; }