How to use fetch multiple api using using getStaticProps in next js

567 views Asked by At

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?

1

There are 1 answers

0
Michel Floyd On

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 its slug) along with all other posts that have the same tag 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:

postsWithRelatedPosts(where:{slug: String!}):[Post]

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:

Type PostWithRelatedPost {
  post: Post
  relatedPosts: [Post]
}

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.