inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

Next + React Query로 SNS 서비스 만들기

dynamic page에서의 API 호출, 코드상 질문 드립니다.

199

이석희

작성한 질문수 2

0

export default function Page({ params }: { params: { postId: number } }){ }  

다음과 같이 app/(Logined)/home/Post/[postId]/page.tsx 에서 params를 불러왔을 때,
prisma와 REST API를 이용하여 데이터를 요청하고 가져오는 것을 할 때,

1.page가 params.postId를 이용하여 NextRequest를 요청하면
2. route.ts가 해당 Request를 받고 prisma를 통해 쿼리를 한 뒤,
3. NextResponse로 page에 답장하는 형식을 구현하고자 합니다.

 

근데 해당 구현에 대해서, 공식 문서에서 제가 해당 내용을 잘 응용하지 못하는 것인지,

GET http://localhost:3000/api/post/4 500 (Internal Server Error)에러만 발생하고 'post'를 불러오지 못하고 있습니다. 이에 눈에 띄는 코드 오류는 없는지 핵심 부분이 빠진 것은 없는지 질문 드립니다.

// app/(Logined)/home/Post/[postId]/page.tsx
"use client";
import React, { useEffect, useState } from "react";
import { PostType } from "@/app/(Logined)/_components/TYPE_post";

export default function Page({ params }: { params: { postId: number } }) {
  const [post, setPost] = useState<PostType | null>(null);
  const postid = params.postId;

  useEffect(() => {
    const fetchPostData = async () => {
      try {
        const response = await fetch(`/api/post/${postid}`);
        if (response.ok) {
          const postData: PostType = await response.json();
          setPost(postData);
        } else {
          console.error("Error fetching post");
        }
      } catch (error) {
        console.error("Error:", error);
      }
    };

    if (params.postId) {
      fetchPostData();
    }
  }, [params.postId]);

  if (!post) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>Post Details</h1>
      <p>Description: {post.description}</p>
      <p>Event Date: {post.eventDate.toString()}</p>
      <p>Deadline: {post.deadline.toString()}</p>
    </div>
  );
}

 

// pages/api/post/[postId]/route.ts
import prisma from "@/app/lib/prisma";
import { NextResponse, NextRequest } from "next/server";

export async function GET(req: NextRequest) {
  const postId = parseInt(req.nextUrl.searchParams.get("postId") || "0");

  if (!postId) {
    return new NextResponse(JSON.stringify({ message: "Invalid post ID" }), {
      status: 400,
    });
  }

  try {
    const post = await prisma.post.findUnique({
      where: { id: postId },
      select: {
        description: true,
        eventDate: true,
        deadline: true,
      },
    });

    if (post) {
      return new NextResponse(JSON.stringify(post));
    } else {
      return new NextResponse(JSON.stringify({ message: "Post not found" }), {
        status: 404,
      });
    }
  } catch (error) {
    console.error("Error fetching post:", error);
    return new NextResponse(
      JSON.stringify({ message: "Error fetching post" }),
      { status: 500 }
    );
  }
}

react next.js rest

답변 1

0

제로초(조현영)

콘솔에 에러 메시지 없나요? 어디까지 실행되고 에러가 발생한 건지 알아야 합니다.

캡처링부분 질문있습니다.

0

78

2

깃에 소스코드를 찾을 수 없습니다.

0

116

2

useInfiniteQuery promise와 react use 사용시 페이지 무한 로딩

0

99

1

import 파일 경로를 찾지 못 해서 에러가 발생합니다.

0

112

2

css 라이브러리 추천 부탁드립니다

0

143

2

팔로우 추천 목록이 빈 배열로 들어옵니다.

0

135

1

게시물 업로드 시 userId가 undefined로 들어가는 오류

0

121

1

useSuspenseQuery 사용 시 SSR 401 이슈 관련

0

173

1

리액트 쿼리 useinfinitequery 무한스크롤 구현 시 페이지가 이동할 경우 데이터가 보존되게 할 수 있나요??

0

189

3

폴링이 필요없는 이유

0

95

2

next Request Memoization과 react cache

0

112

2

seo 최적화 기준은 데이터 fetching인가요 아님 데이터 렌더링인가요?

0

86

2

next.js 서버fetch 에러 fallback ui 구현 방법

0

174

2

프레임워크 여론 파악법

0

127

2

필터옵션이 많은 페이지에서 서버 fetch를 하는게 맞는걸까요??

0

105

2

서버 fetch suspense 로 감싸고 새로고침 시 잠시 빈 화면이 노출된 후 fallback ui가 노출됩니다.

0

106

2

template.tsx 내 서버fetch 응답값과 클라이언트 컴포넌트 상태값 싱크가 맞지 않는 이슈

0

68

2

Auth.js 사용 시 authorize 함수가 호출되지 않습니다

0

134

2

next.js 에서 로그인에 관하여

0

141

1

Next의 route handler에 대한 질문이 있습니다.

0

102

2

게시판 리스트 만들때 use client를 어디서부터 집어넣어야할지 모르겠습니다

0

102

2

프라이빗 폴더를 해야 하는 이유가 모호한 것 같아요.

0

87

2

vanilla-extract 못찾는 문제

0

231

2

fetch 캐싱과 revalidate 관련

0

87

2