React

[React] Promise.all() , Suspense | ์—ฌ๋Ÿฌ ๋น„๋™๊ธฐ ํ•จ์ˆ˜ ์ตœ์ ํ™”

jjingle 2024. 3. 20. 16:41

๊ธฐ์กด ์ฝ”๋“œ

  • ๋น„๋™๊ธฐ์ ์œผ๋กœ 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