Next.js

[Next.js] fetch data, React vs Next.js

jjingle 2024. 3. 19. 16:18

client component์—์„œ ๊ธฐ์กด์˜ API์™€ ์†Œํ†ตํ•˜๋˜ ๋ฐฉ์‹

  • useEffect 
  • useState -> metadata ์‚ฌ์šฉ ๋ถˆ๊ฐ€
  • ๋กœ๋”ฉ state ๊ตฌํ˜„
'use client';

import { useEffect, useState } from 'react';

/* useState์˜ ์‚ฌ์šฉ์œผ๋กœ ์ธํ•ด, ์‚ฌ์šฉ ๋ถˆ๊ฐ€๋Šฅ
export const metadata = {
  title: 'Home',
};
*/

export default function Page() {
  const [isLoading, setIsLoading] = useState(true);
  const [movies, setMovies] = useState([]); //useState -> interactive component๋ฅผ ์‚ฌ์šฉํ•˜๊ฒ ๋‹ค. -> "use client" ์ž‘์„ฑ ํ•„์š”
  const getMovies = async () => {
    const response = await fetch('URL');
    const json = await response.json();

    setMovies(json);
    setIsLoading(false);
  };

  useEffect(() => {
    getMovies();
  }, []);

  return <div>{isLoading ? 'Loading...' : JSON.stringify(movies)}</div>;
}

 

(Next.js ํ”„๋ ˆ์ž„์›Œํฌ ์‚ฌ์šฉ) server component์—์„œ fetch

  • useEffect, useState ์‚ฌ์šฉ ์—†์ด ๋™์ผํ•œ ๊ธฐ๋Šฅ ๊ตฌํ˜„ ๊ฐ€๋Šฅ
  • Next.js ๋Š” ์ž๋™์œผ๋กœ fetch๋œ url์„ ์บ์‹ฑํ•œ๋‹ค -> ์ƒˆ๋กœ๊ณ ์นจ ์‹œ, ๋‹ค์‹œ fetch X
    • Loading ์ƒํƒœ๊ฐ€ ์—†๋‹ค? -> no, ์ฒ˜์Œ fetch ํ•  ๋•Œ API๊ฐ€ ๋Š๋ฆฌ๋‹ค๋ฉด ๋ฐœ์ƒ ๊ฐ€๋Šฅ 
    • ํ•˜์ง€๋งŒ ๋ฐฑ์—”๋“œ์—์„œ fetchํ•˜๊ณ ์žˆ๊ธฐ ๋•Œ๋ฌธ์—, ๋กœ๋”ฉ ์ƒํƒœ๋™์•ˆ web page ์ž์ฒด๋ฅผ ๋ณด์—ฌ์ฃผ์ง€ ์•Š์Œ 
// /app/page.tsx
export const metadata = {
  title: 'Home',
};

const URL = 'URL';

async function getMovies() {
  // const response = await fetch(URL);
  // const json = await response.json();
  // return json;

  //์œ„ ์ฝ”๋“œ๋ฅผ ์ค„์ธ ๊ฒƒ
  return fetch(URL).then(response => response.json());
}

//์–ด๋–ค ์ผ์ด ๋ฐœ์ƒํ•˜๊ธฐ๋ฅผ ๊ธฐ๋‹ค๋ฆฌ๋ ค๊ณ  ํ•  ๋•Œ, await ์‚ฌ์šฉ -> await๋Š” async ํ•จ์ˆ˜ ์•ˆ์—์„œ๋งŒ ์‚ฌ์šฉ ๊ฐ€๋Šฅ
export default async function HomePage() {
  const movies = await getMovies();
  return <div>{JSON.stringify(movies)}</div>;
}
  • (page.tsx ํŒŒ์ผ๊ณผ ๊ฐ™์€ ์œ„์น˜์—) loading.tsx ํŒŒ์ผ์„ ๋งŒ๋“ค์–ด์ฃผ๋ฉด, ํ”„๋ ˆ์ž„์›Œํฌ๋Š” ํ•ด๋‹น ํŒŒ์ผ์„ ์ž๋™์œผ๋กœ loading page component๋กœ ๋ฐ”๊พผ๋‹ค.
    • ๋ฐฑ์—”๋“œ ์„œ๋ฒ„์—์„œ ์‘๋‹ต ๋Œ€๊ธฐ ์‹œ, ์œ ์ €๋Š” ์›นUI๋ฅผ ๊ธฐ๋‹ค๋ฆฌ๋Š”๊ฒŒ ์•„๋‹ˆ๊ณ   loading component ๋ฅผ ๋ฐ”๋กœ ๋ณด๊ฒŒ๋จ.
    • ๋ฐฑ์—”๋“œ ์„œ๋ฒ„ ์‘๋‹ต ์™„๋ฃŒ ์‹œ, ํ”„๋ก ํŠธ์—”๋“œ ํ”„๋ ˆ์ž„์›Œํฌ๋Š” loading component ๋Œ€์‹  ๊ธฐ์กด page ๋ Œ๋”๋ง
// /app/loading.tsx
export default function Loading(){
	return <h2>Loading...</h2>
}

'Next.js' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Next.js] Server component vs Client component  (0) 2024.03.19
[Next.js] Library vs Framework  (1) 2024.03.15
[Next.js] CSR(client side render) vs SSR(server side render)  (0) 2024.03.15
[Next.js] Next ํ”„๋กœ์ ํŠธ ์ˆ˜๋™ setup  (0) 2024.03.14