Skip to main content

usePreviewNode Hook

The usePreviewNode hook provides an abstraction around getting preview data for any post type. When calling the usePreviewNode hook on an appropriate preview page, the hook will ensure authorization, make a request to determine the post type, then make a subsequent request to retrieve the proper preview data. When using 0.7.2 of FaustWP or later, preview data will be retrieved with one request.

The usePreviewNode hook will return an object with the following properties:

  • typeName: The GraphQL type name of the preview node (e.g. Post, Page). Notice the GraphQL types are capitalized.
  • node: The preview node in question. Faust.js is unable to determine the proper GraphQL type for this node, as the types live in your schema.generated.ts file. As a result, casting this node to the proper type is recommended.

The following example shows how to use the usePreviewNode hook to render the default post/page post types:

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

export default function Preview() {
const isLoading = client.useIsLoading();
const { typeName, node } = client.auth.usePreviewNode();

if (isLoading || node === undefined) {
return <p>loading...</p>;
}

if (node === null) {
return <p>Post not found</p>;
}

switch (typeName) {
case 'Page': {
return <PageComponent page={node as Page} />;
}
case 'Post': {
return <PostComponent post={node as Post} />;
}
default: {
throw new Error(`Unspecified post type preview: ${typeName}`);
}
}
}

Additionally, the usePreviewNode hook can be used to get preview data for any custom post type. Say we have a custom post type called Event:

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

export default function Preview() {
const isLoading = client.useIsLoading();
const { typeName, node } = client.auth.usePreviewNode();

if (isLoading || node === undefined) {
return <p>loading...</p>;
}

if (node === null) {
return <p>Post not found</p>;
}

switch (typeName) {
case 'Page': {
return <PageComponent page={node as Page} />;
}
case 'Post': {
return <PostComponent post={node as Post} />;
}
case 'Event': {
const event = node as Event;

return (
<>
<h1>{event.title()}</h1>
<p>{event.content()}</p>
</>
)
}
// Add additional custom post types here as needed
default: {
throw new Error(`Unspecified post type preview: ${typeName}`);
}
}
}