Web Dev/5. Projects

[toy blog service] getServerSideProps 이용하기

hYhY1234 2021. 4. 18. 23:13
728x90

data fetching 중 getStaticProps, getStaticPaths(static build in dynamic route), getServerSideProps 중 마지막 것을 사용해보았다. 이건 간단하게 write 페이지에서 글을 업데이트 중일때는 getServerSideProps를 통해서 serverSide에서 data를 fetching했다. 

 

이건 nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering여기서 확인할 수 있다. 

 

Basic Features: Data Fetching | Next.js

Next.js has 2 pre-rendering modes: Static Generation and Server-side rendering. Learn how they work here.

nextjs.org

 

import Head from "next/head";
import React, { useState } from "react";
import dynamic from "next/dynamic";
import { GetServerSideProps } from "next";

const DynamicComponentWithNoSSR = dynamic(
  () => import("hayoung-markdown").then((mod) => mod.App),
  {
    ssr: false,
  }
);

export const getServerSideProps: GetServerSideProps = async (context) => {
  const articleId = context.query.id ? context.query.id : undefined;

  if (!articleId) {
    const data = "";
    return {
      props: {
        data,
      },
    };
  }

  const data = `Update Article ${articleId}`;
  return {
    props: {
      data,
    },
  };
};

interface Props {
  data: string;
}

const UserWrite: React.FC<Props> = ({ data }) => {
  const contents = data;

  const handleTrigger = (str: string) => {
    return str;
  };

  return (
    <div>
      <Head>
        <title>UserWrite</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      {process.browser ? (
        <DynamicComponentWithNoSSR
          passedContents={contents}
          handleTrigger={handleTrigger}
        />
      ) : null}
    </div>
  );
};

export default UserWrite;

이부분은코드가 딱히 어렵지는 않다. 나는 "http://localhost:3000/hayoung/write?id=4" 식으로 article Id가 있으면 수정중이라고 판단할거고, "http://localhost:3000/hayoung/write" 는 새로운 글을 작성하는 것으로 생각할 것이기때문에 getServerSideProps는 server에 해당 요청이 올때마다 실행 될건데, 이때 id가 있으면 data fetching을해주고 있다. (아니라도 공백 문자열을 넘겨주고 있다)