Skip to content

5: Suspense #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: 04-data-fetching
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions app/star-wars/people/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { type Person } from '../../types';
import { Suspense } from 'react';
import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import sleep from '@/util/sleep';
Expand All @@ -15,6 +16,25 @@ async function getPerson(id: string): Promise<Person> {
return json;
}

async function Starships({ starships }: { starships: string[] }) {
await sleep();
const ships = await Promise.all(
starships.map(async (ship) => {
const res = await fetch(ship);
const json = await res.json();
return json;
})
);

return (
<ul>
{ships.map((ship) => (
<li key={ship.name}>{ship.name}</li>
))}
</ul>
);
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
const person = await getPerson(params.id);

Expand All @@ -40,6 +60,39 @@ export default async function Page({ params }: Props) {
<dd>{person.mass}</dd>
<dt>Hair Color</dt>
<dd>{person.hair_color}</dd>
<dt>Star Ships</dt>
<dd>
<Suspense
fallback={
<div className="flex gap-2 items-center">
<svg
className="animate-spin h-5 w-5 text-sky-500"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
stroke-width="4"
></circle>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
Loading...
</div>
}
>
{/* @ts-expect-error Async Server Component */}
<Starships starships={person.starships} />
</Suspense>
</dd>
</dl>
</div>
);
Expand Down