updated image loading
This commit is contained in:
@@ -1,91 +1,84 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { SightingWidgetType } from "../types/types";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
export function useSightingFeed(
|
||||
baseUrl: string,
|
||||
{
|
||||
limit = 7,
|
||||
pollMs = 800,
|
||||
autoSelectLatest = true,
|
||||
}: {
|
||||
limit?: number;
|
||||
pollMs?: number;
|
||||
autoSelectLatest?: boolean;
|
||||
} = {}
|
||||
) {
|
||||
const [items, setItems] = useState<SightingWidgetType[]>(
|
||||
() => Array(limit).fill(null) as unknown as SightingWidgetType[]
|
||||
// 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<SightingWidgetType[]>(
|
||||
() => Array(7).fill(null) as unknown as SightingWidgetType[]
|
||||
);
|
||||
const [noSighting, setNoSighting] = useState(false);
|
||||
const [selectedRef, setSelectedRef] = useState<number | null>(null);
|
||||
const [mostRecent, setMostRecent] = useState<SightingWidgetType | null>(null);
|
||||
|
||||
const mostRecentRef = useRef<number>(-1);
|
||||
const lastSeenRef = useRef<number | null>(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]);
|
||||
|
||||
// effective selected (fallback to most recent)
|
||||
const selected = useMemo(
|
||||
() =>
|
||||
selectedRef == null
|
||||
? null
|
||||
: items.find((x) => x?.ref === selectedRef) ?? null,
|
||||
[items, selectedRef]
|
||||
: sightings.find((s) => s?.ref === selectedRef) ?? null,
|
||||
[sightings, selectedRef]
|
||||
);
|
||||
|
||||
const effectiveSelected = selected ?? mostRecent ?? null;
|
||||
|
||||
useEffect(() => {
|
||||
let delay = pollMs;
|
||||
let dead = false;
|
||||
const controller = new AbortController();
|
||||
|
||||
async function tick() {
|
||||
try {
|
||||
// Pause when tab hidden to save CPU/network
|
||||
if (document.hidden) {
|
||||
setTimeout(tick, Math.max(delay, 2000));
|
||||
return;
|
||||
}
|
||||
|
||||
const url = `http://100.116.253.81/mergedHistory/sightingSummary?mostRecentRef=${mostRecentRef.current}`;
|
||||
const res = await fetch(url, { signal: controller.signal });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
|
||||
const obj: SightingWidgetType = await res.json();
|
||||
if (obj && typeof obj.ref === "number" && obj.ref > -1) {
|
||||
setItems((prev) => {
|
||||
const next = [obj, ...prev].slice(0, limit);
|
||||
// maintain selection if still present; otherwise select newest if allowed
|
||||
const stillExists =
|
||||
selectedRef != null && next.some((x) => x?.ref === selectedRef);
|
||||
if (autoSelectLatest && !stillExists) {
|
||||
setSelectedRef(obj.ref);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
setMostRecent(obj);
|
||||
mostRecentRef.current = obj.ref;
|
||||
delay = pollMs; // reset backoff on success
|
||||
}
|
||||
} catch {
|
||||
// exponential backoff (max 10s)
|
||||
delay = Math.min(delay * 2, 10000);
|
||||
} finally {
|
||||
if (!dead) setTimeout(tick, delay);
|
||||
}
|
||||
}
|
||||
|
||||
const t = setTimeout(tick, pollMs);
|
||||
return () => {
|
||||
dead = true;
|
||||
controller.abort();
|
||||
clearTimeout(t);
|
||||
};
|
||||
}, [baseUrl, limit, pollMs, autoSelectLatest, selectedRef]);
|
||||
|
||||
return {
|
||||
items,
|
||||
sightings,
|
||||
selectedRef,
|
||||
setSelectedRef,
|
||||
mostRecent,
|
||||
effectiveSelected,
|
||||
mostRecentRef,
|
||||
isPending,
|
||||
noSighting,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user