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: Therefetchfunction returned from auseFetchdata-fetching hook likeusePage. 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 anotheruseFetchhook) and needs to reflect live changes. You simply pass therefetchfunction from your data hook intouseLivePreview.// 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.enableLiveUpdatesis set totruewhen you instantiate yourCMSClient. If it isfalseor undefined, this hook will do nothing. The hook also internally checks for apreviewTicket, so it will only activate when the application is in a valid preview mode. There's no need to conditionally call the hook yourself.