Next 13 서버컴포넌트에서 클라이언트 컴포넌트로 props 전달할 때 Error: Maximum call stack size exceeded

:D ·2023년 6월 12일
2

Error 🤯

목록 보기
4/4

에러 상황

next.js (app directory) 에서 서버 컴포넌트에서 클라이언트 컴포넌트로 pre-fetch 데이터 전달하던 도중에 Error: Maximum call stack size exceeded 문제가 생겼다.

WHY?

왜 에러가 생겼는가에 대해 찾는데에 시간은 좀 걸렸지만, react-query를 잘 못 작성했나? hydrate, hydrate 구조를 잘 못 작성했나? 싶었지만 서버 컴포넌트에서 클라이언트 컴포넌트로 데이터를 전달할 때 문제가 생긴다는 사실을 알게되었다.

그때 app directory 공부를 할 때 Next.js 공식문서에서 서버 컴포넌트에서 클라이언트 컴포넌트에서 props를 전달할 때 주의해야한다고 적혀있던게 기억이 나서 공식문서를 다시 봤다.

Passing props from Server to Client Components (Serialization)

Props passed from the Server to Client Components need to be serializable.
이렇게 적혀있는데 서버 컴포넌트에서 클라이언트 컴포넌트에서 props를 전달할 때 직렬화가 가능해야한다는 것이다.

JSON.stringify()가 가능해야한다는 것이다. JSON으로 변환이 불가능하면 에러가 발생한다.

해결방안

변경 전 코드는 Promise 객체를 리턴하여 JSON.stringify()가 안된다.
이를 Promise 객체에서 data를 추출해 리턴하는 것으로 수정했다.

변경 전

const getCommunityIdCards = (id: string, pageParam: number) => {
  return publicApi.get<BaseResponseType<CommunityIdCardsResponse>>(
    `/communities/${id}/idCards?page=${pageParam}&size=10`,
  );
};

변경 후

const getCommunityIdCards = async (id: string, pageParam: number) => {
  const res = await publicApi
    .get<BaseResponseType<CommunityIdCardsResponse>>(
      `/communities/${id}/idCards?page=${pageParam}&size=10`,
    )
    .then(res => res.data)
    .catch(err => err.response.data);
  return res;
};```
profile
강지영입니...🐿️

0개의 댓글