Tailwind Logo

Retrieving a list of contents using Fetch in Next.js

Content Hub ONENext.js

Published: 2024-08-07

Next.js includes a mechanism to retrieve and process external data using the fetch function. This time, we would like to use this to retrieve the title of the Blog.

Create API

As a general-purpose API for the project, we will create a function that returns data once the value of a GraphQL query is retrieved. The actual code can be viewed in its entirety on GitHub by clicking on the following URL.

The operation is described as follows: c

  • Pass query as string to fetchGraphQL
    • apiKey and endpointUrl values are read from .env.local files
  • Use the fetch function to post a query to the endpointUrl specified above, using the apiKey.
  • When json data is correctly obtained, json data is returned.

Now you can use GraphQL queries to fetchGraphQL to retrieve Json data.

Note that the following calls are made when fetch is used.

TypeScript
    return await fetch(endpointUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-GQL-Token": apiKey,
      },
      body: JSON.stringify({ query }),
      next: { revalidate: 60 },
    })

There is a next: { revalidate: 60 } statement at the end for the GraphQL endpoint. It is updated and cached every 60 seconds when the query is executed.

Create a Query

Add a Query definition to be passed to fetchGraphQL that you have created. This time, we added the following code to the interfaces/Blog/index.ts file. While using the AllBlog query we created last time, we change the sort order to AllBlogQuery, and this time we only retrieve the minimum amount of data. c

TypeScript
export const AllBlogQuery = `query AllBlog {
    allBlog(orderBy: PUBLISHDATE_DESC) {
        total
        results {
            id
            name
            publishDate
            slug
            title
            description
        }
    }
}
`

As a result of running the program in Postman, the following data was obtained.

choneblog01.png

Change page.tsx

We are ready to go. app/page.tsx, which is the home page of Next.js, has been gutted and updated as follows.

TypeScript
import { fetchGraphQL } from "@/utils";
import { Blog, AllBlogResponse, AllBlogQuery } from "@/interfaces/Blog";

export default async function Home() {
  const results: AllBlogResponse = (await fetchGraphQL(
    AllBlogQuery
  )) as AllBlogResponse;

  const posts: Partial<Blog>[] = [];

  results.data.allBlog.results.forEach((post: Partial<Blog>) => {
    posts.push({
      id: post.id,
      name: post.name,
      publishDate: post.publishDate,
      slug: post.slug,
      title: post.title,
      description: post.description,
    });
  });

  return (
    <main>
      <h1>Content Hub ONE - Title list</h1>
      <ul>
        {posts.map((post) => (
            <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </main>
  );
}

The code is introduced from above,

  • Importing pre-created code with import
  • Get data as AllBlogResponse using Query
  • Convert AllBlogResponse data to a Blog array called posts
  • extract and arrange only the titles in posts

The code is very simple. The result is as follows

choneblog02.png

Reflect on GitHub

First, apply the above code to the development branch. For the staging environment previously linked to the development branch of Vercel, the Preview value was set so that unpublished content is also displayed. c

choneblog03.png

Now we will reflect the data from the development branch on the main branch. Since only one content is published, only one content is displayed as shown below.

choneblog04.png

Summary

We actually changed the top page of Next.js to display a list of contents. Using environment variables, we were also able to confirm that the contents are displayed in different destinations for staging and production. Although only the title is displayed on the top page, if data can be acquired and displayed, it will be a first step.

The code up to this point is saved in the following branch

Tags