3

I working on the following piece of code:

It's a blogPost dynamic page: /post/[slug].tsx

export const getStaticPaths: GetStaticPaths = async () => {
  const allSlugs = await getAllSlugs();;
  return ({
    paths: allSlugs.map((slug) => ({ params: { slug }})),
    fallback: "blocking"
  });
};

export const getStaticProps: GetStaticProps = async (context) => {
  const slug = context.params.slug;
  const blogPost = getBlogPostFromSlug({slug});
  return ({
    props: {
      blogPost
    }
  });
};

This is the error I'm getting:

enter image description here

It seems that the GetStaticProps type is generic and can be customized for my types.

enter image description here

I created those two types to try to customize the GetStaticProps type:

type ContextParams = {
  slug: string
}

type PageProps = {
  blogPost: null | Types.BlogPost.Item
}

Here is what I'm trying:

export const getStaticProps: GetStaticProps<PageProps,ContextParams> = async (context) => {
  const slug = context.params.slug;
  const blogPost = await getBlogPostFromSlug({slug});
  return ({
    props: {
      blogPost
    }
  });
};

But it still thinks that params might be undefined. Should I just deal with it? From the code above, does it seem like params could be undefined? I wasn't expecting that.

cbdeveloper
  • 27,898
  • 37
  • 155
  • 336

1 Answers1

8

The types are defined such that the params variable must still be undefined even when you declare the type for the params Q. From the types file:

export type GetStaticPropsContext<Q extends ParsedUrlQuery = ParsedUrlQuery> = {
  params?: Q
...

So if you want to be safe then you should assume that you might not have params. I would use the notFound or redirect properties explained here to handle requests with with missing params. You also want to handle cases where your async function getBlogPostFromSlug was rejected.

export const getStaticProps: GetStaticProps<PageProps, ContextParams> = async (
  context
) => {
  const slug = context.params?.slug;
  if (slug) {
    try {
      const blogPost = await getBlogPostFromSlug({ slug });
      return {
        props: {
          blogPost
        }
      };
    } catch (error) { }
  }
  return {
    notFound: true
  };
};

Typescript Playground Link

Linda Paiste
  • 38,446
  • 6
  • 64
  • 102