import { useEffect, useMemo, useState } from 'react'; import { loadFromApi, type LoadJson, } from '@/components/PackagesProvider/PackagesProvider'; import useHydrated from '@/hooks/useHydrated'; import { hostCmsData } from '@/lib/cmsData'; import { mapHero, type HeroData } from '@/lib/hero'; const HERO_PATH = '/api/v1/hero'; const TIMEOUT_MS = 8000; // The hero to show: the one in the data block the CMS host wrote, else the // one the API gives, else the baked one. Failing safe is the rule: a missing // block, a network error, a 204, a time-out or an answer that cannot be used // leaves the baked hero on screen. The block is only read after hydration, // so the first render equals the prerendered HTML. export default function useHero( baked: HeroData, load: LoadJson = loadFromApi, ): { hero: HeroData; regionHero: HeroData } { const hydrated = useHydrated(); const fromBlock = useMemo(() => { const block = hydrated ? hostCmsData(document) : null; return block?.hero === undefined ? null : mapHero(block.hero); }, [hydrated]); const [fetched, setFetched] = useState(null); useEffect(() => { // The host sent the data: nothing to ask if (hostCmsData(document)) return; const controller = new AbortController(); const { signal } = controller; const timer = setTimeout(() => controller.abort(), TIMEOUT_MS); load(HERO_PATH, signal) .then((answer) => { const mapped = mapHero(answer); if (mapped && !signal.aborted) setFetched(mapped); }) .catch(() => undefined) .finally(() => clearTimeout(timer)); return () => { clearTimeout(timer); controller.abort(); }; }, [load]); // regionHero is what the plain HTML region of the page holds: the baked // hero, or the one the API gave. The block of the host does not count: the // host wrote that region itself and it must not be written over (that // would replace the photo the browser has painted). return { hero: fromBlock ?? fetched ?? baked, regionHero: fetched ?? baked, }; }