캘린더 시작날과 종료일을 설정하여 데이터를 가져오다가
오늘 날짜로부터 일주일 전까지,
오늘 날짜로부터 열흘 전까지 데이터 가져오기 등의 기능을 만들게 되었고, new Date를 state에 적용하여 사용해봄
첫 클릭에 setState가 적용되지 않아서 렌더링의 변화가 없는 이슈 생김 -> 초기값과 set에 조정이 필요하다고 생각함
// 첫 클릭 시 날짜 변동이 화면에 그려지지 않는 이슈 발생
// 렌더링 이슈라면 -> setState에서 문제가 의심되어서 초기값을 변경해보기로 함
const today = new Date();
let dayBefore = new Date();
dayBefore.setDate(today.getDate() - 7);
const [startDate, setStartDate] = React.useState(dayBefore);
const [endDate, setEndDate] = React.useState(today);
const today = new Date(); // 오늘 날짜 가져옴. endDate는 계속 이 날로 넣을거고, startDate는 이 날을 기준으로 +- 할것임
const dayBefore = new Date(); // 계속 변화하는 startDate 로 사용 예정
const [startDate, setStartDate] = React.useState(
new Date(dayBefore.setDate(today.getDate() - 7))
);
// 초기값에 값을 직접 넣었더니 값이 숫자로 나옴 (날짜가 밀리세컨즈로 나옴)
// new Date 형태로 감싸주어 날짜형태로 변환
const [endDate, setEndDate] = React.useState(today);
// 버튼 코드
{selectedPeriod.map((round, index) => {
return (
<div
key={index}
className="w-16 h-6 leading-7 bg-gray-100 rounded-xl mr-2 "
onClick={() => {
dayBefore.setDate(today.getDate() - round);
setStartDate(dayBefore);
setEndDate(today);
}}
>
{round}일
</div>
);
})}
// 11월 1일이 되었는데 이틀전을 누르면 갑자기 9월 29일이 되는 이슈 발생
// 초기값은 7일전인 10/25로 세팅이 정상적으로 되는데 버튼을 누르면 날짜는 맞고, 달이 9월로 바뀜 .. -> 버튼 누르는 이슈가 있었던 듯
const today = new Date();
const defaultDay = new Date(today).setDate(today.getDate() - 7);
// 그냥 초기값은 dayBefore 변수와 구분짓고, 한 번만 사용할 새로운 변수를 할당
const dayBefore = new Date(today);
const [startDate, setStartDate] = React.useState(new Date(defaultDay));
const [endDate, setEndDate] = React.useState(today);
// -> 초기값은 다른 변수로 따로 관리했더니 날짜를 변경해도 이상한 일이 생기지 않았다.
// 날짜 연산 예시
let today = new Date();
// 1년 후
today.setFullYear(today.getFullYear()+1)
// 45일 전
today.setDate(today.getDate()- 45)