Skip to main content

usePreviewContext

This hook fetches the context for a given preview ticket, which is typically read from the URL. It's most often used to get the correct redirect URL when entering a preview session.

Usage

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

const { data: previewContext, isLoading } = usePreviewContext();

if (previewContext?.redirectURL) {
// perform redirect
}

Return Value

The hook returns a standard useFetch object, where data has the following shape:

  • redirectURL (string | null): The redirect URL provided by the CMS for the preview session.
  • catalogVersions (string[]): An array of catalog versions available in the preview system.

Deep Dive

Description: usePreviewContext is a specialized hook for handling the initial handshake of a CMS preview session. When a user clicks a "preview" link from a CMS (like SmartEdit), they are sent to the Archibald application with a temporary "ticket". This hook uses that ticket to ask the backend, "Where should I actually go, and what content should I show?".

  • How To: Use this hook in a dedicated component that runs when a cmsTicketId is present in the URL query parameters. This component will be responsible for redirecting the user to the correct page for the preview.

    // Correct: A component to handle the preview redirect.
    import { usePreviewContext } from '@archibald/cms';
    import { useLocation, Redirect } from 'react-router-dom';

    function PreviewRedirector() {
    const location = useLocation();
    const hasTicket = new URLSearchParams(location.search).has('cmsTicketId');

    // Only run the hook if the ticket exists.
    const { data: previewContext, isLoading } = usePreviewContext({
    enabled: hasTicket
    });

    if (isLoading) {
    return <div>Loading Preview...</div>;
    }

    if (previewContext?.redirectURL) {
    return <Redirect to={previewContext.redirectURL} />;
    }

    return null; // Or render a "preview failed" message
    }
  • Best Practice: Always use the enabled option to ensure the hook only runs when a preview ticket is actually present. Firing the hook on every page load without a ticket is unnecessary and will result in a failed network request. The component using this hook should typically be placed high in your routing tree to intercept preview requests early.