I am currently in the process of setting up a new blog using a combination of nextJS, TypeScript, and sanity CMS. The homepage is already set up to display posts perfectly. Next on my list is to display the details of each post when it is clicked, based on its individual slug. So far, I have been able to successfully fetch the data for the blog posts by calling the query inside the sanity dashboard.
https://i.stack.imgur.com/rissA.png
Here are the 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,
}
}
I encountered the following error:
Error: getStaticPaths was added without a getStaticProps in /post/[slug].
Without getStaticProps, getStaticPaths does nothing