import type { PlacesLibraryDetailResponse, PlacesLibraryKind } from '@trek/shared'; import { useCallback, useEffect, useState } from 'react'; import { placesLibraryRepo } from '../../repo/placesLibraryRepo'; /** * One place as All places reads it (every trip and list it sits in, what each * keeps of it), for a view that opens from somewhere else: a list's place opens * the same place view as All places, so it reads the same thing. Offline or on an * error the view keeps its own part and the tabs stay empty. * * `revision` is the view's own copy of the place: whenever it changes (a status, * a vote, an edit, a remote change) the place is read again, so the tabs follow. * What was read for another place is never shown for this one. */ export function useLibraryPlace(kind: PlacesLibraryKind, id: number | null, revision?: unknown) { const [held, setHeld] = useState<{ key: string; data: PlacesLibraryDetailResponse | null } | null>(null); const [seq, setSeq] = useState(0); const key = id == null ? null : `${kind}:${id}`; useEffect(() => { if (id == null) return; const ctrl = new AbortController(); const readKey = `${kind}:${id}`; placesLibraryRepo .detail(kind, id, ctrl.signal) .then((res) => { if (!ctrl.signal.aborted) setHeld({ key: readKey, data: res }); }) .catch(() => { // Nothing to show beside the list's own part; the tabs read as empty. if (!ctrl.signal.aborted) setHeld({ key: readKey, data: null }); }); return () => ctrl.abort(); }, [kind, id, seq, revision]); const reload = useCallback(() => setSeq((n) => n + 1), []); const data = held !== null && held.key === key ? held.data : null; return { data, reload }; }