Skip to content

Commit 87b5bc7

Browse files
committed
End of part 10
1 parent ab82853 commit 87b5bc7

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import { UnsplashUser } from "@/models/unsplash-user";
2+
import { Metadata } from "next";
3+
import { notFound } from "next/navigation";
4+
import { cache } from "react";
5+
import { Alert } from "@/components/bootstrap";
6+
7+
interface PageProps {
8+
params: { username: string },
9+
}
10+
11+
async function getUser(username: string): Promise<UnsplashUser> {
12+
const response = await fetch(`https://api.unsplash.com/users/${username}?client_id=${process.env.UNSPLASH_ACCESS_KEY}`);
13+
14+
if (response.status === 404) notFound();
15+
16+
return await response.json();
17+
}
18+
19+
// const getUserCached = cache(getUser) Use cache if you're not using the native fetch
20+
21+
export async function generateMetadata({ params: { username } }: PageProps): Promise<Metadata> {
22+
const user = await getUser(username);
23+
24+
return {
25+
title: ([user.first_name, user.last_name].filter(Boolean).join(" ") || user.username) + " - NextJS 13.4 Image Gallery",
26+
}
27+
}
28+
29+
export default async function Page({ params: { username } }: PageProps) {
30+
const user = await getUser(username);
31+
32+
return (
33+
<div>
34+
<Alert>
35+
This profile page uses <strong>generateMetadata</strong> to set the <strong>page title</strong> dynamically from the API response.
36+
</Alert>
37+
38+
<h1>{user.username}</h1>
39+
<p>First name: {user.first_name}</p>
40+
<p>Last name: {user.last_name}</p>
41+
<a href={"https://unsplash.com/" + user.username}>Unsplash profile</a>
42+
</div>
43+
);
44+
}

src/models/unsplash-user.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
export interface UnsplashUser {
2+
username: string,
3+
first_name: string,
4+
last_name: string,
5+
}

0 commit comments

Comments
 (0)