참치코더의 꿈 메모장

Next.js / API 서버 호출 및 동시 호출 방법 정리(코드 위주) 본문

Next.js

Next.js / API 서버 호출 및 동시 호출 방법 정리(코드 위주)

참치깡 2025. 10. 5. 18:25
728x90

 

제미나이가 생성한 Next.js 이미지

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import Link from "next/link"
 
export const metadata = {
    title: "Home",
}
 
export const API_URL = "https://nomad-movies.nomadcoders.workers.dev/movies";
 
async function getMovies(){
    
    // 1. return fetch(URL).then(response => response.json()); -> 해당 URL에 있는 값을 json 형식으로 변경해서 가져온다.
    
    // 2. 같은 의미로 풀어서 나온 코드
    const response = await fetch(API_URL);
    const json = await response.json();
    return json;
 
}
 
 
export default async function HomePage(){
    const movies = await getMovies();
    return (
        <div>
            {movies.map((movie) => (
                <li key = {movie.id}>
                    <Link href={`/movies/${movie.id}`}>{movie.title}</Link>
                </li>
            ))}
        </div>
    );
}
 
cs

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import {API_URL} from "../../../(home)/page";
 
async function getMovie(id:string){
    console.log(`Fetching movies: ${Date.now()}`);
    await new Promise((resolve) => {setTimeout(resolve, 5000)});
    const response = await fetch(`${API_URL}/${id}`);
    return await response.json();
}
 
async function getVideos(id:string){
    console.log(`Fetching videos: ${Date.now()}`);
    await new Promise((resolve) => {setTimeout(resolve, 5000)});
    const response = await fetch(`${API_URL}/${id}/videos`);
    return await response.json();
}
 
export default async function MovieDetail({
    params,
}: {
    params: Promise<{id: string}> // params로 들어오는 id값이 String인 값인 것을 약속하는 것이다.
}){
    console.log("===============");
    console.log('start fetching');
    
    const {id} = await params; // 구조분해 할당 : id = params.id
    
    // Promise.all을 사용하면 동시에 값을 fetch해서 가져올 수 있다.
    const[movie, videos] = await Promise.all([getMovie(id), getVideos(id)]);
    console.log('end fetching');
 
    return (
        <>
            <h1>{movie.title}</h1>
            <ul>
                {videos.map((video: any) => (
                    <li key = {video.id}>{video.name}</li>
                ))}
            </ul>
        </>
    );
};
cs

 

- Promise.all을 사용하면, 해당 fetch되는 파일들을 한번에 백엔드 서버(Next.js에서 가져오게된다.)

- 노마드 코더 강의 공부 후 (정리본)

728x90
Comments