Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation
The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post based on the slug (postID). However, it was discovered that running Prisma inside body components is not feasible. Subsequently, the solution involves employing getStaticProps and getStaticPaths to query the post by its ID prior to build time.
Code
/post/[...slugs].tsx
The URL structure resembles:
localhost:3000/post/postID/PostTitle
For example:
localhost:3000/post/b513-ad29e3cc67d9/Post%20Title
import { Post, PrismaClient } from '@prisma/client';
import { GetStaticPaths, GetStaticProps } from 'next';
import { useRouter } from 'next/router';
type postByIdProps = {
postById: Post
}
export default function PostDetail({postById}: postByIdProps) {
return (
<>
<div>
{postById.title}
</div>
</>
);
}
export const getStaticProps = async(context: any)=>{
// React Hooks cannot be used here, creating a challenge in obtaining the slug name without the hook.
const router = useRouter();
const slugs: any = router.query.slugs;
const postId = slugs?.[0].toString()
//Prisma
const prisma = new PrismaClient()
const postById = prisma.post.findUnique({
where: {
postId: postId,
},
})
return postById
}
export const getStaticPaths: GetStaticPaths<{ slug: string }> = async () => {
return {
paths: [], //indicates that no page needs be created at build time
fallback: 'blocking' //indicates the type of fallback
}
}