Skip to main content

usePreview Hook

The usePreview hook provides an abstraction around getting a preview page or post from the Headless WordPress API. When calling the usePreview hook on an appropriate preview page, the hook will determine if the preview is a page or post and will make a request to retrieve the proper preview content.

The following example shows how to use the usePreview hook to render either a post or page from WordPress:

src/pages/preview.tsx
import { PageComponent } from './[...pageUri]';
import { PostComponent } from './posts/[postSlug]';
import { client } from 'client';

export default function Preview() {
const { usePreview } = client.auth;
const result = usePreview();

if (client.useIsLoading() || !result) {
return <p>loading...</p>;
}

if (result.type === 'page') {
if (!result.page) {
return <>Not Found</>;
}

return <PageComponent page={result.page} />;
}

if (!result.post) {
return <>Not Found</>;
}

return <PostComponent post={result.post} />;
}