[TIL] 내배캠4기-NextJs-103일차_Timestamp.toDate()

hare·2023년 2월 12일
0

내배캠-TIL

목록 보기
70/75

AS-IS

Date.now()로 들어간 날짜데이터 값 -> number타입

파이어스토어 db 예시

에러 발생

커뮤니티 페이지에서 작성날짜 순으로 정렬 후 표시하기 위해서 다음과 같은 코드를 작성하였다.

const newPosts = snapshot.docs.map((doc) => {
  const newPost = {
    id: doc.id,
    title: doc.data().title,
    editorText: doc.data().editorText,
    writtenDate: doc.data().writtenDate.toDate().toString(),
  };
  return newPost;
});

writtenDate.toDate()에서 에러를 뱉어냈다.
Date.now()는 number 타입으로 취급되기 때문에 toDate()가 Date객체에만 사용할 수 있는 메소드기 때문에 발생한 에러였던 것이다.

The Date.prototype.toDateString() method can only be used on the Date object and not on any other object type
참고블로그

TO-BE

Timestamp.toDate(): Date
Converts a Timestamp to a JavaScript Date object. This conversion causes a loss of precision since Date objects only support millisecond precision.

@returns
JavaScript Date object representing the same point in time as this Timestamp, with millisecond precision.

방법은 여러 가지 있었는데 나의 경우에는

const newPost = {
  title,
  content,
  writtenDate: Timestamp.now(),
};

날짜 키값을 Timestamp.now()로 수정해주고 db에 타입형까지 object로잘 변경되어 들어간 것도 확인하고 코드를 다시 돌려봤다.
역시 object.toDate() -> 에러없음






[참고]
https://binaryjourney.tistory.com/21
https://itsjavascript.com/javascript-typeerror-todatestring-is-not-a-function.

profile
해뜰날

0개의 댓글