44 lines
1.2 KiB
JavaScript
44 lines
1.2 KiB
JavaScript
/**
|
|
* useNavContext
|
|
*
|
|
* Provides prev/next artwork IDs scoped to the same author via API.
|
|
*/
|
|
import { useCallback } from 'react';
|
|
|
|
// Module-level cache for API calls
|
|
const fallbackCache = new Map();
|
|
|
|
async function fetchFallback(artworkId) {
|
|
const key = String(artworkId);
|
|
if (fallbackCache.has(key)) return fallbackCache.get(key);
|
|
|
|
try {
|
|
const res = await fetch(`/api/artworks/navigation/${artworkId}`, {
|
|
headers: { Accept: 'application/json' },
|
|
});
|
|
if (!res.ok) return { prevId: null, nextId: null, prevUrl: null, nextUrl: null };
|
|
const data = await res.json();
|
|
const result = {
|
|
prevId: data.prev_id ?? null,
|
|
nextId: data.next_id ?? null,
|
|
prevUrl: data.prev_url ?? null,
|
|
nextUrl: data.next_url ?? null,
|
|
};
|
|
fallbackCache.set(key, result);
|
|
return result;
|
|
} catch {
|
|
return { prevId: null, nextId: null, prevUrl: null, nextUrl: null };
|
|
}
|
|
}
|
|
|
|
export function useNavContext(currentArtworkId) {
|
|
/**
|
|
* Always resolve via API to guarantee same-user navigation.
|
|
*/
|
|
const getNeighbors = useCallback(async () => {
|
|
return fetchFallback(currentArtworkId);
|
|
}, [currentArtworkId]);
|
|
|
|
return { getNeighbors };
|
|
}
|