-
[NextJS] getServerSideProps, getStaticProps 사용Programming/JavaScript & TypeScript 2022. 9. 7. 08:07728x90
NextJS를 Typescript로 사용하는 것은 항상 타입에 대한 고민을 하게 된다.
대부분 JS로 예제가 많아서 getServerSideProps, getStaticProps의 타입을 적어둔다.
server-side-rendering은 페이지가 들어와서 서버에 데이터를 요청할 때마다 갱신
static-side-rendering은 빌드타임에 한번만 서버에서 가져온 데이터를 가져오고, 그걸 local에 보관
근데, NextJS는 왜 static-side를 추천하는것인지...의문임-> revalidate 를 이용해서 특정 시간 후에 계속 갱신할 수 있는 옵션이 있었음!!!!!!그러면 이걸 써야지...
-> props뒤에 revalidate를 사용하자
코드만 간단히 적어둔다.
큰 차이는 props를 받는 component에서 어떻게 달라지는지이다.
ServerSideRendering
const Home: NextPage = ({posts}:InferGetServerSidePropsType<GetServerSideProps>) => {
StaticSideRendering
const Home: NextPage = ({posts}:InferGetStaticPropsType<typeof getStaticProps>) => {import type {GetStaticProps, InferGetServerSidePropsType, InferGetStaticPropsType, NextPage} from 'next' import { useEffect, useState } from 'react' import {GetServerSideProps} from 'next' import styles from '../styles/Home.module.css' import {RecipeObject} from "../types/RecipeObject"; import Group from "../components/Group"; type Post = { userId:number id:number title:string body:string } //const Home: NextPage = ({posts}:InferGetServerSidePropsType<GetServerSideProps>) => { const Home: NextPage = ({posts}:InferGetStaticPropsType<typeof getStaticProps>) => { const [data, setData] = useState<RecipeObject[] | null>([]) const [postss, setPosts] = useState<Post[] | null>(null) useEffect(() => { const getRecipe = async () => { const res = await fetch('api/getConfigRecipe') const data = await res.json() setData(data.result) } setPosts(posts) getRecipe() }, []) return ( <div className={styles.container}> <main className={styles.main}> <h1 className={styles.title}> Welcome to ThinQ Home Admin </h1> {data!= null && <Group data={data}/> } <ul>{postss !== null && postss.map((item, index) => ( (<li key={index}> {item.title}</li>)) )} </ul> </main> </div> ) } /*fetch는 두 가지 방법 https://velog.io/@devstone/Next.js-100-%ED%99%9C%EC%9A%A9%ED%95%98%EA%B8%B0-feat.-initialProps-webpack-storybook#-getserversideprops https://javascript.plainenglish.io/how-to-automatically-get-props-types-in-next-js-and-typescript-4c223e962617 SSR(Server Side Rendering), SSG(Static Site Generation) */ //페이지에 들어올때마다 서버에 요청해서 데이터 받아옴 //서버에서 빈번한 변경이 있을 때...사용 export const getServerSideProps:GetServerSideProps = async (context) => { const res = await fetch('https://jsonplaceholder.typicode.com/posts?_start=0&_end=10') const posts = await res.json() //여기서 return 한 값이 Home에 props들어간다. return { //props: {posts:posts} props:{posts:posts} } } //개발모드에서는 큰 차이를 볼 수 없음, npm run build를 해서 봐야함 //빌드타임에 가져오고, 그 다암부터는 안가져온다. //nextjs에서는 statisSideProps를 추천한다...왜? export const getStaticProps:GetStaticProps = async (context) => { const res = await fetch('https://jsonplaceholder.typicode.com/posts?_start=0&_end=10') const posts = await res.json() return { //{posts:posts}나 posts를 하나만 써도 됨.... props:{posts}, revalidate:20 } } export default Home
출처
'Programming > JavaScript & TypeScript' 카테고리의 다른 글
[NextJS] getStaticPaths (0) 2022.09.07 [NextJS] 외부 주소에서 이미지 가져올 때.. (0) 2022.09.07 playwright를 알아보자 (0) 2022.07.04 Javascript에서의 this (0) 2022.05.24 Skeleton UI (0) 2022.05.20