0

The blog itself and the live preview for the home page (where you can see all the posts) works fine, but when I tried to implement it for a single post I got this error: TypeError: Cannot read properties of null (reading 'mainImage')

<Image
  44 |   className="object-cover object-center mx-auto"
> 45 |   src={urlFor(post.mainImage).url()}
     |                   ^
  46 |   alt={post.author.name}
  47 |   fill
  48 | />

Here's the code for a single post:

export async function generateStaticParams() {
  const query = groq`
        *[_type == "post"]
        {
            slug
        }
        `;

  const slugs: Post[] = await client.fetch(query);
  const slugRoutes = slugs.map((slug) => slug.slug.current);

  return slugRoutes.map((slug) => ({
    slug,
  }));
}

 
export default async function HomePage({ params: { slug } }: Props) {
  const query = groq`
  *[_type == "post" && slug.current == $slug][0] {
      ...,
      author->,
      categories[]->,
  }
`;
const post: Post = await client.fetch(query, { slug });

if (draftMode().isEnabled) {
  return (
    <PreviewSuspense
      fallback={
        <div role="status">
          <p className="text-center text-lg animate-pulse text-[#F7AB0A]">
            Loading Preview Data...
          </p>
        </div>
      }
    >
      <PreviewPost query={query} />
    </PreviewSuspense>
  );
}
 
  return <Post post={post} />;
 }

And here's the code for the PreviewPost component:

"use client";

import { usePreview } from "../lib/sanity.preview";
import Post from "./Post";

type Props = {
    query: string;
};

export default function PreviewPost({ query }: Props) {
    const post = usePreview(null, query);
    return <Post post={post} />;
}

What am I missing?

Vilmos Szabó
  • 167
  • 1
  • 2
  • 10

0 Answers0