Previously, we used the page.tsx file to retrieve the blog title, but we will separate the part that retrieves the blog data and implement it in a way that is easy to reuse.
Organize the code on the page
In the previous article, we described how to get GraphQL data in the page.tsx file, but to make it generic, we first create the src/utils/getBlog/index.ts file. The code is in the form of the code used in src/app/page.tsx in a separate file.
TypeScript
import { AllBlogQuery, AllBlogResponse, Blog } from "@/interfaces/Blog";
import { fetchGraphQL } from "@/utils";
export async function getAllBlog() {
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 posts;
}
The separation makes it possible to retrieve the blog data using the getAllBlog function. page.tsx file is simplified as follows
TypeScript
import { getAllBlog } from "@/utils/getBlog";
export default async function Home() {
const posts = await getAllBlog();
return (
<main>
<h1>Content Hub ONE - Title list</h1>
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</main>
);
}
The function part created in the previous version is defined in another file. The result of the operation is the same as the previous one.
Summary
When the schema of the Blog is changed, for example, as in this case, the interface definition can be changed and the values of the corresponding functions can be changed to make it easier to understand where the modifications have been made.