Live Preview With NextJS/Sanity
dsosborn opened this issue · comments
I'm trying to implement the new preview functionality on an existing project in a very simple way on the home page. It works fine until I actually put the PreviewProvider on the HomePage page.tsx file. I get this error:
./src/app/page.tsx
ReactServerComponentsError:
You're importing a component that needs next/headers. That only works in a Server Component but one of its parents is marked with "use client", so it's a Client Component.
Learn more: https://nextjs.org/docs/getting-started/react-essentials
,-[/Users/douosbor/epsilon-repos/citrusad-website/src/app/page.tsx:1:1]
1 | import { SanityDocument } from "next-sanity";
2 | import { sanityFetch, token } from "$/utils/sanityFetch";
3 | import { mainNavQuery } from "$/utils/groq-queries";
4 | import { draftMode } from "next/headers";
: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5 | import PreviewHome from "./_components/PreviewHome";
6 | import PreviewProvider from "$/utils/PreviewProvider";
`----
Am I missing something? Here's the code on src/app/page.tsx:
import { SanityDocument } from "next-sanity";
import { sanityFetch, token } from "$/utils/sanityFetch";
import { mainNavQuery } from "$/utils/groq-queries";
import { draftMode } from "next/headers";
import PreviewHome from "./_components/PreviewHome";
import PreviewProvider from "$/utils/PreviewProvider";
export const TestComponent = ({ code }: { code: {} }) => (
<main className={"theme__background"}>
<h1>This is a humble start.</h1>
<pre>{JSON.stringify(code, null, 2)}</pre>
</main>
);
export default async function Home() {
const posts = await sanityFetch<SanityDocument[]>({ query: mainNavQuery });
const isDraftMode = draftMode().isEnabled;
if (isDraftMode && token) {
return (
<PreviewProvider token={token}>
<PreviewHome posts={posts} />
</PreviewProvider>
);
}
return <TestComponent code={posts} />;
}
Still not sure what the above issue was, but as this next/sanity preview landscape seems to be changing rapidly, I had success following this starter template: https://github.com/sanity-io/sanity-template-nextjs-app-router-personal-website
Yeah, App Router itself has been changing itself. We can then either choose to rapidly keep up with it, or stagnate 😅
In any case, we'll always keep our templates up-to-date with what's current best practice!