๊ธฐ์กด ์ฝ๋
- ๋น๋๊ธฐ์ ์ผ๋ก getMovie ํจ์๊ฐ ์คํ๋๊ณ ์๋ฃ ํ, getVideo ํจ์ ์คํ
- => ๋ฐ์ดํฐ ์์ด ๋ง์ ๊ฒฝ์ฐ ๋นํจ์จ์
async function getMovie(id: string) {
const response = await fetch(`${API_URL}/${id}`);
return response.json();
}
async function getVideos(id: string) {
const response = await fetch(`${API_URL}/${id}/videos`);
return response.json();
}
//dynamic route
export default async function MovieDetail({ params: { id } }: { params: { id: string } }) {
const movie = await getMovie(id);
const video = await getVideos(id);
return <h1>{movie.title}</h1>;
}
1 ์ฐจ ์ต์ ํ : Promise.all()
- ๋น๋๊ธฐ ํจ์ ๋๊ฐ ๋์์ ํธ์ถ -> ๊ฒฐ๊ณผ๊ฐ์ array์ ๊ฐ๊ฐ ๋ด์ ๋ฐํ
- ๋ณ๋ ฌ fetch => but. ๋ ํจ์ ๊ฐ ๋ชจ๋ ๋๋ ๋ ๊น์ง ๊ธฐ๋ค๋ ค์ผํจ
async function getMovie(id: string) {
const response = await fetch(`${API_URL}/${id}`);
return response.json();
}
async function getVideos(id: string) {
const response = await fetch(`${API_URL}/${id}/videos`);
return response.json();
}
export default async function MovieDetail({ params: { id } }: { params: { id: string } }) {
// const movie = await getMovie(id);
// const video = await getVideos(id);
const [movie, video] = await Promise.all([getMovie(id), getVideos(id)]);
return <h1>{movie.title}</h1>;
}
2์ฐจ ์ต์ ํ : Suspense
- 1์ฐจ ์ต์ ํ๋ก ๋์์ ํจ์ ์คํ -> ๋จผ์ ๋๋ ํจ์๋ถํฐ render
- Suspense ์ฌ์ฉ์ ์ํด, ๊ฐ๊ฐ์ ํจ์๋ฅผ component๋ก ๋๋๊ณ suspense๋ก ๊ฐ์ผ๋ค
- fallback prop of Suspense : component๊ฐ await ๋๋ ๋์ ํ์๋ (loading) ๋ฉ์ธ์ง render
// movie-info.tsx
async function getMovie(id: string) {
const response = await fetch(`${API_URL}/${id}`);
return response.json();
}
export default async function MovieInfo({ id }: { id: string }) {
const movie = await getMovie(id);
return <h1>{movie.title}</h1>;
}
//movie-video.tsx
async function getVideos(id: string) {
const response = await fetch(`${API_URL}/${id}/videos`);
return response.json();
}
export default async function MovieVideos({ id }: { id: string }) {
const videos = await getVideos(id);
return <h6>{JSON.stringify(videos)}</h6>;
}
// page.tsx
export default async function MovieDetail({ params: { id } }: { params: { id: string } }) {
return (
<div>
<Suspense fallback={<h1>Loading movie info</h1>}>
<MovieInfo id={id} />
</Suspense>
<Suspense fallback={<h1>Loading movie videos</h1>}>
<MovieVideos id={id} />
</Suspense>
</div>
);
(์ฝ๋ ์ถ์ฒ : nomad corder)
'React' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[React] Vite + React + TS ๊ฐ๋ฐ ์๋ฒ ๊ตฌ์ถ (1) | 2024.02.26 |
---|---|
[React] React Hooks (0) | 2023.09.15 |