usePreviewNode Hook
This doc assumes you're storing your pages/styles/etc. in a directory called src
, and you have the baseUrl
option set to src
in your tsconfig.json
for importing modules from the root.
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 yourschema.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:
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
:
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}`);
}
}
}