방법에는 여러가지가 있습니다. 그래서 애플리케이션의 사용 용도에 따라서 다른 방법을 사용해주시면 됩니다.
보통 React에서는 데이터를 가져올 때 useEffect안에서 가져옵니다. 하지만 NextJS에서는 다른 방법을 사용해서 가져오게됩니다.
getStaticProps : Static Generation으로 빌드(build)할 때 데이터를 불러옵니다.
export async function getStaticProps(context) {
return {
props: {}, // will be passed to the page component as props
}
}
getStaticProps 함수를 async로 export하면 getStaticProps에서 리턴되는 props를 가지고 페이지를 pre-render합니다.
getStaticPaths :
return {
paths: [
{ params: { id: '1' } },
{ params: { id: '2' } }
],
fallback: ...
}
// If the page is not yet generated, this will be displayed
// initially until getStaticProps() finishes running
if (router.isFallback) {
return <div>Loading...</div>
}
getServerSideProps 함수를 async로 export 하면 Next는 각 요청마다 리턴되는 데이터를 getServerSideProps로 pre-render합니다.
function Page({ data }) {
// Render data...
}
// This gets calledon every request
export async function getServerSideProps() {
// Fetch data from external API
const res = await fetch(`https://.../data`)
const data = await res.json()
// Pass data to the page via props
return { props: { data } }
}
export default Page