TypeError: Date is not a constructor 오류 해결

GOGO·2024년 8월 6일

date picker로 날짜를 조정하고, Home 컴포넌트에 띄우려고 했는데 TypeError: Date is not a constructor 오류 발생

첨에는 날짜 형식이 잘못 받아진 거라고 생각해서

let formattedDate;
try {
  // Date 파싱 시도
  let date = new Date(cafe.date);
  // 유효하지 않은 날짜일 경우, ISO 형식으로 변환 시도
  if (isNaN(date)) {
    date = new Date(cafe.date.replace(/-/g, '/'));
  }
  // 여전히 유효하지 않은 경우 에러 발생
  if (isNaN(date)) {
    throw new Error('Invalid Date');
  }
  formattedDate = date.toLocaleDateString();
} catch (error) {
  console.error(`Invalid date for cafe entry: ${cafe.date}`, error);
  formattedDate = 'Invalid date';
}

이렇게 검사해봤는데 2024-07-31T06:45:03.586Z 형식으로 잘 나오는듯 함...

계속 데이터를 불러오는 부분에서만 오류를 찾다가 스택 오버플로에서 해결방법을 찾았다
https://stackoverflow.com/questions/30130241/typeerror-date-is-not-a-constructor

Date는 날짜와 시간을 처리하는 내장 객체라서 변수명을 Date로 명명하면 충돌이 일어날 수 있다.

그러고보니 styleComponents를 사용하면서

const Date = styled.p`
  font-size: 13px;
  color: #7A7A7A;
  font-weight: 500;
`;

이렇게 변수명을 설정했던 것...

변수명 바꿔주고 문제 해결

profile
#💻 #FE #💡 #📓

0개의 댓글