The category page
You can find the working example for this lesson in the
code/05-next-ssg/05.16-category-page
folder.
The last thing to do before our application is ready is to create a category page. It will contain a list of posts from a given category. Again, we will start with API.
Category API#
Let's create a new endpoint at /categories/:id
. We use id
as category identifier and search for posts that have the category
field with the same value:
xxxxxxxxxx
app.get("/categories/:id", (req, res) => {
const { id } = req.params
const found = posts.filter(({ category }: Post) => category === id)
const categoryPosts = [found, found, found]
return res.json(categoryPosts)
})
Then we repeat the list of found posts 3 times, just to make it look longer than it really is. In a real-world API, we would instead make a request to a database and pull a list of category posts from there.
Now we need to create a function for fetching category data. Create a new file api/category.ts
with the following contents:
xxxxxxxxxx
import fetch from "node-fetch"
import { Post, EntityId } from "../shared/types"
import { config } from "./config"
​
export async function fetchPosts(
categoryId: EntityId
): Promise<Post[]> {
const url = `${config.baseUrl}/categories/${categoryId}`
const res = await fetch(url)
return await res.json()
}
The function fetchPosts()
takes a category identifier EntityId
and returns a Promise
of Post[]
.
Define the staticPaths
for the category page. Open shared/staticPaths.ts
and add the following imports:
xxxxxxxxxx
import { EntityId, Category } from "./types"
Define the CategoryStaticParams
and CategoryStaticPath
types:
xxxxxxxxxx
type CategoryStaticParams = {
id: Category
}
​
type CategoryStaticPath = {
params: CategoryStaticParams
}
The Category
page component#
Next we want to create the Category
page component. First of all, let's design props for it. The Category
component should take a list of Post
items as the posts
prop:
This lesson preview is part of the Fullstack React with TypeScript Masterclass course and can be unlocked immediately with a single-time purchase. Already have access to this course? Log in here.
Get unlimited access to Fullstack React with TypeScript Masterclass with a single-time purchase.
