I have a [slug].js page where I'm using getStaticPath
and getStaticProps
to fetch the data and create static page{
export async function getStaticProps({ params }) {
const { posts } = await hygraph.request(
`
query BlogPostPage($slug: String!){
posts(where:{slug: $slug}){
id
slug
title
tags
}
}
`,
{
slug: params.slug,
}
);
return {
props: {
posts,
},
};
}
export async function getStaticPaths() {
const { posts } = await hygraph.request(`
{
posts {
slug
}
}
`);
return {
paths: posts.map(({ slug }) => ({
params: { slug },
})),
fallback: false,
};
}
const Post = ({ posts }) => {
return (
<>
<div className='max-w-[1240px] mx-auto mt-3 px-4 lg:flex'>
<BlogPost posts={posts} />
<div className='lg:ml-3 mb-5'>
<div className='lg:sticky lg:top-[74px]'>
<SuggesCard />
</div>
</div>
</div>
</>
)
}
There are two react components: BlogPost
and SuggesCard
, I am sending fetched posts content to BlogPost
but now I want to fetch all the other post titles related to this fetched posts tag. so for this should i make another api call using getStaticPaths/getStaticProps
or should I use a different approach?
There are many ways of solving this problem so expect some opinionated answers.
From what I understand of your question, you want to build a page that contains an individual
post
(identified by itsslug
) along with all other posts that have the sametag
as the individual post.Having the client make two queries feels slow and clumsy to me. The server should have everything it needs in the original slug.
I suggest creating a new query as follows:
Then on the server return all the posts you are looking for. The server would first find the individual post, get its tags, then find all the related posts (excluding the original), concatenate and deduplicate the results, and return all the posts. If you don't want to create another type you could just use the convention that the post you found by slug is the first element in the return array. If that seems too clunky just go ahead and create a new type:
and return that instead. This is more flexible since you can use a different set of fields for the related posts (perhaps you just want the date and title) than for the main post.