Home > Enterprise >  getStaticPaths was added without a getStaticProps - typescript
getStaticPaths was added without a getStaticProps - typescript

Time:05-02

I am creating a blog using nextJS, typescript and sanity CMS. I have created the homepage where the post shows perfectly. next I am fetching the blog post details when I click the post with their individual slug. This query fetch data perfectly when I call it inside sanity dashboard here

This query fetch data perfectly when I call it inside sanity dashboard here:

this is Post typings

export interface Post {
  _id: string
  _createdAt: string
  title: string
  author: {
    name: string
    image: string
  }
  description: string
  mainImage: {
    asset: {
      url: string
    }
  }
  slug: {
    current: string
  }
  body: [object]
}

[slug].tsx:

import { GetStaticProps } from 'next'
import Header from '../../components/Header'
import { sanityClient, urlFor } from '../../sanity'
import { Post } from '../../typings'

interface Props {
  post: Post
}
function Post({ post }: Props) {
  //   console.log(post)
  return (
    <main>
      <Header />
      {/* <img src={urlFor(post.mainImage).url()} alt="" /> */}
    </main>
  )
}

export default Post
export const getStaticPaths = async () => {
  const query = `*[_type == "post"]{
        _id,
        slug{
            current
        }
    }`
  const posts = await sanityClient.fetch(query)
  const paths = posts.map((post: Post) => ({
    params: {
      slug: post.slug.current,
    },
  }))

  return {
    paths,
    fallback: 'blocking',
  }
}
export const GetStaticProps: GetStaticProps = async ({ params }) => {
  const query = `*[_type == "post" && slug.current == $slug][0]{
  _id,
  _createdAt,
  title,
  author-> {
  name,
  image
},
 description,
 mainImage,
 slug,
 body
}`
  const post = await sanityClient.fetch(query, {
    slug: params?.slug,
  })

  if (!post) {
    return {
      notFound: true,
    }
  }
  return {
    props: {
      post,
    },
    revalidate: 60,
  }
}

The error I am getting is:

Error: getStaticPaths was added without a getStaticProps in /post/[slug]. 
Without getStaticProps, getStaticPaths does nothing

CodePudding user response:

Your problem is you defined getStaticProps wrongly. If you notice that your definition is GetStaticProps (the first letter is capitalized) which is not getStaticProps (the function of Next.js' life cycle)

For the fix, you just need to modify it to getStaticProps: GetStaticProps

export const getStaticProps: GetStaticProps = async ({ params }) => {
  const query = `*[_type == "post" && slug.current == $slug][0]{
  _id,
  _createdAt,
  title,
  author-> {
  name,
  image
},
 description,
 mainImage,
 slug,
 body
}`
  const post = await sanityClient.fetch(query, {
    slug: params?.slug,
  })

  if (!post) {
    return {
      notFound: true,
    }
  }
  return {
    props: {
      post,
    },
    revalidate: 60,
  }
}
  • Related