1

I'm developing a blog using nextJS & sanity. And I connected sanity with nextJS and it's perfectly working in development mode. But when I try to deploy in Vercel or build through the VSCode, it shows the below error.

info  - Generating static pages (0/8)TypeError: Cannot destructure property 'title' of 'post' as it is undefined.

Here is my component overview

export default function SinglePost({ post }) {
  const {
    title,
    imageUrl,
    publishedAt,
    description,
    topics,
    rescources,
    sourcecode,
    body = [],
  } = post;
return(
<div>
    <h1>{title}</h1>
    //remaining code....
</div>)
}
const query = groq`*[_type == "post" && slug.current == $slug][0]{
  "title": title,
  "imageUrl": mainImage.asset->url,
  description,
  "topics": topics[],
  "rescources": rescources[],
  "sourcecode": sourcecode,
  "publishedAt": publishedAt,
  body,
  
}`;

export async function getStaticPaths() {
  const paths = await client.fetch(
    `*[_type == "post" && defined(slug.current)][].slug.current`
  );

  return {
    paths: paths.map((slug) => ({ params: { slug } })),
    fallback: true,
  };
}

export async function getStaticProps(context) {
 
  const { slug = "" } = context.params;
  const post = await client.fetch(query, { slug });
  return {
    props: {
      post,
    },
  };
}
  • 1
    That's most likely due to the `fallback: true` behaviour. See [TypeError: Cannot read property 'title' of undefined NextJS](https://stackoverflow.com/a/73368354/1870780). – juliomalves Sep 21 '22 at 10:46

3 Answers3

0

Hi i found this to work

    const Page: NextPage = (props: any) => {
      const { post = undefined || {} } = props
      const { title = "Undefined title" } = post
      return (
        <>
          <Head>
            <title>{title}</title>
          </Head>
        </>
      )
    }

 

       const query = groq`*[_type == "post" && slug.current == $slug][0]{
      title,
      "name": author->name,
      "authorImage": author->image,
      "categories": categories[]->title,
    }`
    
    export async function getStaticProps(context: any) {
      // It's important to default the slug so that it doesn't return "undefined"
      const { slug = '' } = context.params
      const post = await client.fetch(query, { slug })
      return {
        props: {
          post,
        },
      }
    }

user18371666
  • 71
  • 1
  • 8
0

I was able to solve this problem.

Solution: Without destructuring 'title', I got a value through the direct access

<h1>{post.title}</h1>
0

i got the same issue, the error says prerender-error , I add a if block to handle the fallback :

const PostId = ({postId}) => {


    const router = useRouter()

    if (router.isFallback) {
        return <div>Loading...</div>
    }
    return (
       ...
    )
...
}

and it builds successfully, make sure you handle the fallback in page

Joe Bao
  • 1
  • 1