1

I'm fetching page data from a cms, so far I have only one page in pages/posts.


pages/posts/[slug].js

import { getAllPostsWithSlug, getPostAndMorePosts } from '../../lib/api';

export default function Post({ post }) {
  const router = useRouter();
  const { slug } = router.query;
  return (
    <div>
      <p>
        title: {typeof post == 'undefined' ? 'no post' : post.title}
      </p>
    </div>
  );
}

export async function getStaticProps({ params, preview = null }) {
  const data = await getPostAndMorePosts(params.slug, preview);
  const content = await markdownToHtml(data?.posts[0]?.content || '');

  return {
    props: {
      preview,
      post: {
        ...data?.posts[0],
        content,
      },
      morePosts: data?.morePosts,
    },
  };
}

export async function getStaticPaths() {
  const allPosts = await getAllPostsWithSlug();
  return {
    paths: allPosts?.map((post) => `/posts/${post.slug}`) || [],
    fallback: true,
  };
}

That will correctly display post.title, but if I access the property directly with

<p>title: {post.title}</p>

I get the build error: post undefined

Is next trying to build a page out of the template with no data? When the build succeeds I only have one route in /posts.

agricola
  • 11
  • 1
  • 2
  • Can you share "getAllPostsWithSlug, getPostAndMorePosts" ? – Yilmaz Apr 24 '21 at 08:53
  • CMS fetching functions: https://imgur.com/gallery/obzdEUO The api works fine, and if I include an option to return null in the component if props are undefined the component renders ok, I just don't understand *where* the props are undefined, since there is only one page using this dynamic route... – agricola Apr 24 '21 at 16:09

0 Answers0