• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 Next.js 게시판 getServerSideProps 질문

getServerSideProps 질문

6 글 보임 - 1 에서 6 까지 (총 6 중에서)
  • 글쓴이
  • #109306

    한준서
    참가자
    게시글 리스트 보여주는 페이지 만드려고 하는데 서버기능이랑 프론트를 분리하고 싶어서 서버기능 생성 후 fetch로 요청 넣도록 했습니
    처음엔 useEffect 사용해서 비동기로 fetch 요청 넣도록 했는데, 이러니까 전체 페이지 렌더링이랑 게시글 정보부분 렌더링에 시간차가 납니다
    찾아보니까 getServerSideProps로 해서 SSR을 하면 된다고 하던데, ""getServerSideProps" is not supported in app/" 가 뜨네요
    코드는 page.js 가장 상단에
    export async function getServerSideProps(context) {
      const { board } = context.query;
      const res = await fetch(`http://your-api-endpoint/api/posts?board=${board}`);
      const posts = await res.json();
    
      return {board, posts};
    }
    처럼 작성 했습니다 (예제 그대로 복붙함)
    
    해결법이나 더 좋은 방법 있으면 알려주세요
     
    #109320

    codingapple
    키 마스터
    13이후버전부턴 app폴더면 서버컴포넌트안에 적으면 됩니다
    #109457

    한준서
    참가자
    이미 서버컴포넌트인데 제가 뭘 잘못알고 있는걸까요?? 코드 전문입니다
    경로 : src/app/board/page.js
    import { SortAt, Title, List, Label } from "./pageComponent";
    export async function getServerSideProps(context) {
      const { board } = context.query;
      const res = await fetch(`http://your-api-endpoint/api/posts?board=${board}`);
      const posts = await res.json();
      return {board, posts};
    }
    async function PostList() {
      const req = await post()
      return <List board={board} posts={posts} />;
    }
    export default function BoardPage(){
      return(
        <div className="ml-9">
          <Title/>
          <div className="flex flex-row mt-7 font-['Gsans'] h-7 text-sm">
            <select className="border pl-4 pr-9 w-auto">
              <option>제목</option>
              <option>내용</option>
              <option>작성자</option>
            </select>
            <input className="border ml-1.5 w-1/3 px-1.5"></input>
            <button className="border bg-gray-700 text-white w-1/12 ml-1.5">검색</button>
          </div>
          <div className="flex justify-between mt-[13px] w-[964px]">
            <SortAt/>
            <button className="border rounded-full text-gray-500 text-[17px] font-['Gsans'] h-[23px] px-[28px]">
              글쓰기
            </button>
          </div>
          <Label/>
          <PostList/>
          {/* <List /> */}
          <div className="flex justify-end mt-[56.3px]">
            <select className="border font-['PretendardMedium'] font-[15px]">
              <option>10개씩 보기</option>
              <option>20개씩 보기</option>
              <option>30개씩 보기</option>
            </select>
          </div>
          <div className="flex flex-row justify-center items-center font-['Gsans'] text-[16px] text-gray gap-x-[34px]">
              <button>{'<'}</button>
              <button>{'1'}</button>
              <button>{'2'}</button>
              <button>{'3'}</button>
              <button>{'4'}</button>
              <button>{'5'}</button>
              <button>{'>'}</button>
          </div>
        </div>
      )
    }
    #109490

    codingapple
    키 마스터
    getServerSideProps는 pages폴더에서만 사용가능합니다 
    export default function BoardPage(){ 안에서 fetch 쓰면 됩니다
    
    #109730

    한준서
    참가자
    function List({board, posts}) {
      if(board === 'qna'){
        return (
          <div>
            {posts.map((post) => (
              <Question
                key={post.id}
                title={post.title}
                author={post.author}
                date={post.date}
                nado={post.nado}
                view={post.view}
                comment={post.comment}
              />
            ))}
          </div>
        );
      }
      return (
        <div>
          {posts.map((post) => (
            <Post
              key={post.id}
              title={post.title}
              author={post.author}
              date={post.date}
              recommend={post.recommend}
              scrap={post.scrap}
              view={post.view}
              comment={post.comment}
            />
          ))}
        </div>
      );
    }
    이 부분을 렌더링 하려고 하는데, 처음에는 그냥 fetch로 시도했다가 posts.map is not function 오류가 뜨더라구요...
    정보를 아직 못 받아와서 빈 배열이라 그런거 같아서 처음에 비동기로 useEffect 시도했던거고, 시간차가 나서 여러가지 시도해보고 있는데 잘 안됩니다...
    이럴 때 해결방법 있으면 알려주실 수 있나요??ㅜ
    
    그리고 반드시 프백을 나누는게 좋을까요?? 사실 그냥 프론트쪽에서 db 접속해서 해도 되긴 하는데(강의 초반부처럼),
    이러면 api 부분을 만들 필요도 없지 않나요??
    #109766

    codingapple
    키 마스터
    posts에 뭐 들어있으면 .map()하라고 삼항연산자 씁시다 
    html 자주 바꿔주는 페이지면 클라이언트사이드렌더링이 낫습니다
6 글 보임 - 1 에서 6 까지 (총 6 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠