Next.js Study - getStaticProps/ getServerSideProps

박윤택·2021년 10월 17일
3

next.js

목록 보기
1/2
post-thumbnail

getServerSideProps

import fetch from 'isomorphic-unfetch';

const name = ({ user }) => {
  const username = user && user.name;
  return <div>{username}</div>
}

export const getServerSideProps = async ({ query }) => {
  console.log(query)
  const { name } = query;
  try {
    const res = await fetch(`https://api.gethub.com/users/${name}`);
    if(res.status === 200){
      const user = await res.json();
      return { props: { user } };
    }
    return { props: {} };
  } catch(e){
    console.log(e);
    return {props: {} };
  }
}

export default name;

서버 측에서 props를 받아오는 기능
페이지 요청 시마다 실행, 데이터를 서버에서 렌더링
query를 props로 사용

getStaticProps

import fetch from "isomorphic-unfetch";

const name = ({user, time}) => {
  const username = user && user.name;
  return (
    <div>
      {username}
      {time}
    </div>
  );
}

export const getStaticProps = async ({ params }) => {
  try {
    const res = await fetch(`https://api.github.com/users/${params.name}`);
    const user = await res.json();

    if(res.status === 200){
      const user = await res.json();
    return {props: {user, time: new Date().toISOString() }};
    }
    return {props: {time: new Date().toISOString()}}
  } catch(e) {
    console.log(e);
    return {props: {time: new Date().toISOString()}}
  }
}

export async function getStaticPaths() {
  return {
    paths: [{params: {name: "jerrynim"}}],
    fallback: true,
  }
}

export default name;

query 대신 params를 사용
getStaticPath()를 이용하여 params미리 지정필요
fallback이 false이면 이외의 경로는 404 에러 페이지로 이동
getStaticPaths는 페이지의 경로가 외부 데이터에 의존할 때 사용

getServerSideProps Vs getStaticProps

getServerSide는 빌드와 상관없이 매 요청마다 데이터를 서버로부터 가져오지만 getStaticProps는 빌드시 고정되는 값, 빌드이후에는 변경이 불가능

0개의 댓글