포스트상세페이지([id].tsx
)에서 getServerSideProps에서 url에서 id를 받아(query)
id로 getDoc 한개의 포스트를 조회해서 가져오는데
createdAt이라는 타임스탬프 타입 속성이 return할때 에러가 남.
return {
props: {
...data,
},
};
이렇게 작성했더니
Reason: object ("[object Date]") cannot be serialized as JSON. Please only return JSON serializable data types
createdAt: createdAt ? JSON.parse(JSON.stringify(createdAt)) : null,
이런 에러가 남.
createdAt가 타임스탬프라서 json 파싱해서 리턴햇는데 (createdAt: JSON.parse(JSON.stringify(createdAt))
)createdAt.toDate().toLocaleDateString()
이렇게 출력하면
TypeError: createdAt.toDate is not a function
이런 에러가 났다.
에러 원인
createdAt
을 JSON.parse(JSON.stringify(createdAt))
로 변환하면, Firestore의 Timestamp
객체가 일반적인 JSON 객체로 변환되기 때문에 toDate
메서드를 사용할 수 없다. createdAt
을 Date
객체로 변환하려면 getServerSideProps
에서 직렬화 전에 변환해야 한다.
올바른 처리 방법
1. getServerSideProps
에서 Date
객체로 변환
createdAt
을 Firestore의 Timestamp
에서 Date
로 변환한 후 문자열로 직렬화한다.
export const getServerSideProps = async (context) => {
const doc = await getDoc(docRef);
const data = doc.data();
return {
props: {
post: {
...data,
createdAt: createdAt.toDate().toISOString(),
},
},
};
};
toDate()
를 호출하여Date
객체로 변환.toISOString()
으로 문자열화하면 JSON 직렬화가 가능하다.
2. 클라이언트에서 toLocaleDateString
사용
직렬화된 createdAt
을 클라이언트에서 다시 Date
객체로 변환하여 로컬 날짜 형식으로 출력한다.
const Post = ({ post }) => {
const createdAt = post.createdAt ? new Date(post.createdAt) : null;
return (
<div>
<h1>{post.title}</h1>
<p>{createdAt.toLocaleDateString()}</p>
</div>
);
};
정리
getServerSideProps
에서 FirestoreTimestamp
를 직렬화하려면toDate()
로 변환 후 문자열화해야 한다.- 클라이언트에서
Date
객체로 다시 변환한 후 날짜를 원하는 형식으로 출력한다.
'Frontend > Next.js' 카테고리의 다른 글
yarn berry와 nextjs 프로젝트 생성시 에러 해결모음... (0) | 2024.06.27 |
---|---|
The "images.domains" configuration is deprecated. Please use "images.remotePatterns" configuration instead (1) | 2024.02.14 |
could not open directory "pg_notify": No such file or directory 오류 해결하기 (0) | 2024.02.04 |
Error: Cannot find module '@npmcli/config' 해결하기.. (1) | 2024.02.04 |
Nextjs 프로젝트 git pull/clone 받고 실행 오류 (0) | 2024.02.02 |