Skip to main content

useLivePreview

This hook connects a component's data-fetching logic to the live update events dispatched by a CMS preview environment (e.g., Contentful Live Preview). It should be used on pages that need to update in real-time based on edits made in the CMS.

Usage

The hook requires the refetch function from a useFetch hook (like usePage) to be passed as an argument.

import { usePage, useLivePreview } from '@archibald/cms';

function MyPageComponent() {
const { data, refetch } = usePage({ pageLabelOrId: 'homepage' });

// Attach the live preview listeners
useLivePreview({ refetch });

return (
// ... render page data
);
}

Parameters

  • options (object):
    • refetch: The refetch function returned from a useFetch data-fetching hook like usePage. This function will be called whenever the CMS dispatches a live update event.

Deep Dive

Description: useLivePreview is the essential link for enabling real-time content updates from a CMS. When in a valid preview session, it registers a listener with the CMSClient. When the connected CMS (e.g., Contentful) sends an "updated" event, this listener fires the refetch callback, prompting useFetch to get the latest content for the component.

  • How To: The hook should be called within any page or component that displays data from usePage (or another useFetch hook) and needs to reflect live changes. You simply pass the refetch function from your data hook into useLivePreview.

    // Correct: Using useLivePreview to refetch page data on update.
    import { usePage, useLivePreview } from '@archibald/cms';

    function ProductPage({ productCode }) {
    const { data, refetch } = usePage({
    pageType: 'ProductPage',
    code: productCode
    });

    // Whenever the CMS sends an update event, the usePage query will be refetched.
    useLivePreview({ refetch });

    // ... render page data
    }
  • Best Practice: Ensure that previewOptions.enableLiveUpdates is set to true when you instantiate your CMSClient. If it is false or undefined, this hook will do nothing. The hook also internally checks for a previewTicket, so it will only activate when the application is in a valid preview mode. There's no need to conditionally call the hook yourself.