Skip to content

Instantly share code, notes, and snippets.

@blakewilson
Last active May 24, 2023 13:56
Show Gist options
  • Save blakewilson/56b91a4050ff907b22f88f8e33e32c3e to your computer and use it in GitHub Desktop.
Save blakewilson/56b91a4050ff907b22f88f8e33e32c3e to your computer and use it in GitHub Desktop.
Preview in Faust outside of the Template Hierarchy system
import { gql, useQuery } from '@apollo/client';
import { getApolloAuthClient, useAuth } from '@faustwp/core';
import { useRouter } from 'next/router';
function AuthenticatedView(props) {
const {
query: { typeName, p },
} = useRouter();
const client = getApolloAuthClient();
const postType = typeName.toLowerCase();
// Get preview data using the "typeName" from the preview URl as the post type
const { data } = useQuery(
gql`
query GetPreviewData($id: ID!) {
${postType}(id: $id, idType: DATABASE_ID, asPreview: true) {
title
content
}
}
`,
{
variables: { id: p },
client,
},
);
// Todo: Show different components based on different "postType"
return (
<>
<>{data?.[postType]?.title}</>
<div dangerouslySetInnerHTML={{ __html: data?.[postType]?.content }} />
</>
);
}
export default function Preview(props) {
const { isAuthenticated } = useAuth({
shouldRedirect: true,
});
const { query, isReady } = useRouter();
if (!isReady || isAuthenticated !== true) {
return <>Loading...</>;
}
if (!query.p && !query.typeName) {
return <>Invalid preview URL</>;
}
return <AuthenticatedView props={{ ...props }} />;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment