Node & React basic3 #2

Jay·2023년 5월 31일
0

Node & React basic 3

목록 보기
2/3
post-thumbnail

Data fetching

NextJS에서 데이터를 가져오는 방법을 알아보자.
ReactJS에서는 useEffect를 통해 가져오지만 NextJS에서는 다른 방법을 통해서 가져오게 된다.

  1. getStaticProps
    • Static Generation으로 빌드할 때 데이터를 불러온다.
      (무슨 말인지 잘 모르겠는데 대충 빌드할 때 가져온다는 것이다)
  2. getStaticPaths
    • Static Generation으로 데이터에 기반하여 pre-render시에 특정한 동적 라우팅을 구현할 때 필요한 것이다.
  3. getServerSideProps
    • 요청이 있을 때 데이터를 불러온다.

getStaticProps

getStaticProps함수를 async로 export하면 getStaticProps에서 리턴되는 props를 가지고 페이지를 pre-render한다. build time에 페이지가 렌더링된다.

export async function getStaticProps() {
	const res = await fetch('https://.../posts')
    const posts = await res.json()
}

return {
	props: {
    	posts,
    }
}

보면 async로 export된 정보를 props에 저장했고 이후에 이걸

function Blog({ posts }){
	return {
    	<ul>
        {posts.map((post) => (
        	<li>{post.title}</li>
        ))}
        </ul>
    }
}

이렇게 뿌려줄 수 있다는 것이다.

getStaticProps는 사용자의 요청보다 먼저 빌드 시 필요한 데이터를 가져올 때 사용한다.

getStaticPaths

동적 라우팅이 필요할 때 getStaticPaths로 경로 리스트를 정의하고 HTML에 build시간에 렌더된다.

..진짜 뭔말인지

paths는 어떠한 경로가 pre-render될지를 결정하며, 만약 pages/posts/[id].js라는 이름의 동적 라우팅을 사용하는 페이지가 있다면 아래와 같이 된다.

return {
	paths: [
      { params: { id: '1' } },
      { params: { id: '2' } }
    ],
  	fallback: ...
}

빌드하는 동안 /posts/1/posts/2를 생성하게 되는 것임.

페이지 이름이 pages/posts/[postId]/[commentId]라면 params는 postIdcommentId이다.
만약 페이지 이름이 pages/[...slug]와 같이 모든 경로를 사용한다면, params는 slug가 담긴 배열이어야 한다.

fallback이라는 게 있는데 fallback이 false라면 getStaticPaths로 리턴되지 않는 것은 모두 404페이지가 뜨게 된다.
true라면 getStaticPaths로 리턴되지 않는 것은 404로 뜨지 않고 fallback 페이지가 뜨게 된다.

예시)

if (router.isFallback) {
	return <div>Loading...</div>
}

useEffect랑 비슷한 것도 같고..

function Post({ post }) {
	// Render post...
}

export async function getStaticPaths() {
	const res = await fetch('https://.../posts')
    const posts = await res.json()
    
    const paths = posts.map((post) => ({
    	params: {id: post.id},
    }))
    
    return {paths, fallback: false}
}

보면 getStaticPaths에서 백엔드로 요청한 정보를 fetch 하여 params에 post.id를 담아주고 있다.

export async function getStaticProps({ params }) {
	const res = await fetch(`https://.../posts/${params.id}`)
    const post = await res.json()
    
    return { props: { post } }
}

그런 다음 아까 언급한 getStaticProps를 가지고 위의 코드에서 params를 가져온다음, 그 params를 이용해 post라는 props를 만들 것이다. 또 이 props는 코드 맨 상위에 있는 Post 컴포넌트로 들어갈 것임
그리고 이걸 가지고 render를 하게 되는 것이다.

getServerSideProps

getServerSideProps함수를 async로 export하면 Next는 각 요청마다 리턴되는 데이터를 getServerSideProps로 pre-render한다.

요청을 보낼 때마다 데이터를 가져옴.

function Page({ data }){
	// Render data...
}

export async function getServerSideProps(){
	const res = await fetch('https://.../data')
    const data = await res.json()
    
    return { props: { data } }
}

얘는 요청할 때 데이터를 가져와야 하는 페이지를 미리 렌더해야 할 때 사용한다.

profile
ㄱ이 아닌 개발자가 되고 싶은 사람

0개의 댓글