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

76 lines
2.2 KiB
TypeScript
Raw Normal View History

import { useEffect, useRef, useState } from "react";
2025-09-16 14:20:38 +01:00
import type { SightingType } from "../types/types";
2025-08-20 08:27:05 +01:00
2025-09-16 14:20:38 +01:00
async function fetchSighting(url: string, ref: number): Promise<SightingType> {
const res = await fetch(`${url}${ref}`);
2025-08-22 10:38:28 +01:00
if (!res.ok) throw new Error(String(res.status));
return await res.json();
2025-08-22 10:38:28 +01:00
}
export function useSightingFeed(url: string) {
2025-09-16 14:20:38 +01:00
const [sightings, setSightings] = useState<SightingType[]>([]);
2025-08-20 08:27:05 +01:00
const [selectedRef, setSelectedRef] = useState<number | null>(null);
2025-09-16 14:20:38 +01:00
const [mostRecent, setMostRecent] = useState<SightingType | null>(null);
2025-09-12 08:21:52 +01:00
const [selectedSighting, setSelectedSighting] = useState<SightingType | null>(
null
);
2025-08-20 08:27:05 +01:00
const currentRef = useRef<number>(-1);
const pollingTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
const lastValidTimestamp = useRef<number>(Date.now());
2025-08-20 08:27:05 +01:00
useEffect(() => {
const poll = async () => {
try {
const data = await fetchSighting(url, currentRef.current);
const now = Date.now();
if (data.ref === -1) {
if (now - lastValidTimestamp.current > 60000) {
console.warn("No valid sighting in over a minute. Restarting...");
currentRef.current = -1;
lastValidTimestamp.current = now;
}
pollingTimeout.current = setTimeout(poll, 400);
} else {
currentRef.current = data.ref;
lastValidTimestamp.current = now;
2025-09-12 08:21:52 +01:00
setSightings((prev) => {
const updated = [data, ...prev].slice(0, 7);
return updated;
});
setMostRecent(data);
setSelectedRef(data.ref);
pollingTimeout.current = setTimeout(poll, 100);
}
} catch (err) {
console.error("Polling error:", err);
pollingTimeout.current = setTimeout(poll, 100);
2025-08-20 08:27:05 +01:00
}
};
2025-08-20 08:27:05 +01:00
poll();
2025-08-22 10:38:28 +01:00
return () => {
if (pollingTimeout.current) clearTimeout(pollingTimeout.current);
};
}, [url]);
2025-08-22 10:38:28 +01:00
2025-09-12 08:21:52 +01:00
// const selected = sightings.find(s => s?.ref === selectedRef) ?? mostRecent;
2025-08-20 08:27:05 +01:00
return {
2025-08-22 10:38:28 +01:00
sightings,
2025-08-20 08:27:05 +01:00
selectedRef,
setSelectedRef,
mostRecent,
2025-09-12 08:21:52 +01:00
setSelectedSighting,
selectedSighting,
// effectiveSelected: selected,
2025-08-20 08:27:05 +01:00
};
}