Skip to main content

usePreviewTicket

This hook gets (and can set) the preview ticket identifier from the application's client-side state. It provides a simple way to access the cmsTicketId that may be present in the URL.

Usage

import { usePreviewTicket } from '@archibald/cms';

// Get the current ticket
const [previewTicket] = usePreviewTicket();

// You can also get the setter function
const [ticket, setTicket] = usePreviewTicket();

Return Value

It returns a tuple [string | undefined, (ticket: string) => void] similar to useState.

  • The first element is the current preview ticket.
  • The second element is a function to update the preview ticket in the state.

Deep Dive

Description: usePreviewTicket is a state-management hook that synchronizes the CMS preview ticket (usually from the URL) with a client-side state store. This avoids the need to constantly parse the URL in every component that might need the ticket.

  • How To: Use this hook to retrieve the ticket when you need to pass it along in a subsequent request, for example, when manually constructing a URL that needs to remain in preview mode.

    // Correct: Passing the ticket to a new URL.
    import { usePreviewTicket } from '@archibald/cms';

    function SomeLink({ to, children }) {
    const [previewTicket] = usePreviewTicket();

    const destination = new URL(to, window.location.origin);
    if (previewTicket) {
    destination.searchParams.set('cmsTicketId', previewTicket);
    }

    return <a href={destination.href}>{children}</a>;
    }
  • Best Practice: While you can set the ticket with this hook, it's generally not recommended to do so manually. The state is designed to be set automatically by the framework when it detects the cmsTicketId in the URL upon page load. You should primarily use this hook for reading the ticket. For fetching preview-related data, prefer usePreviewContext, which handles the data fetching lifecycle for you.