[main project day 22] main project

이민선(Jasmine)·2023년 7월 18일
1
post-thumbnail

예약 달력 mock Data에서 API 데이터로 바꾸기

import axios from 'axios';
import BookingDates from '../components/BookingDates';
import Calendars from '../components/Calendars';
import ReservationBtn from '../components/ReservationBtn';
import { BookingPageContainer } from '../style';
import { useParams } from 'react-router-dom';
import { useEffect } from 'react';
import { StartEndDateProps } from '../model/IStartEndDateProps';
import { useDispatch } from 'react-redux';
import { setMonthlyReservation } from '../store/MonthlyReservationStore';

function BookingPage() {
  // GET요청으로 기존 예약 정보 가져오기
  const dispatch = useDispatch();
  interface IMonthlyReservation {
    productTitle: string;
    baseFee: number;
    feePerDay: number;
    minimumRentalPeriod: number;
    reservationsDate1: StartEndDateProps[];
    reservationsDate2: StartEndDateProps[];
  }
  const today = new Date();
  const year = today.getFullYear();
  const currentMonth = (today.getMonth() + 1).toString().padStart(2, '0');
  const nextMonth = (today.getMonth() + 2).toString().padStart(2, '0');

  const { itemId } = useParams<{ itemId: string }>();
  useEffect(() => {
    const getReservation = () => {
      axios
        .get(
          process.env.REACT_APP_API_URL +
            `/api/reservations/products/${itemId}/calendar?date1=${year}-${currentMonth}&date2=${year}-${nextMonth}`,
        )
        .then((res) => {
          console.log('제목', res.data.productTitle);
          console.log('기본료', res.data.baseFee);
          console.log('하루 사용료', res.data.feePerDay);
          console.log('최소 렌탈 기간', res.data.minimumRentalPeriod);
          console.log('이번 달 예약 배열', res.data.reservationsDate1);
          console.log('다음 달 예약 배열', res.data.reservationsDate2);
          // dispatch(setMonthlyReservation(res.data));
        })
        .catch((err) => {
          console.log(err);
        });
    };
    getReservation();
  }, [itemId]);
  return (
    <BookingPageContainer>
      <BookingDates />
      <Calendars />
      <ReservationBtn />
    </BookingPageContainer>
  );
}
export default BookingPage;


GET 요청으로 잘 들어온다.

근데 dispatch로 들어온 데이터들을 전달했더니?

dispatch(setMonthlyReservation(res.data));

예약 데이터에

endDate
: 
"2023-08-02"
startDate
: 
"2023-07-30"

이렇게 전달을 했더니

데이터가 왜 안뜨죠?
7월 30일부터 8월 2일까지는 회색바탕으로 뜨길 기대한건데..

알고보니 며칠 전에 API 명세서에 표시된 데이터 형태대로 mock data를 만들었는데, 다시 보니 mock data와 다르게 바뀌어있었다.

원래 내가 가지고 있는 mock data는

  reservationsDate1: [
    {
      startDate: {
        year: 2023,
        month: 7,
        date: 15,
      },
      endDate: {
        year: 2023,
        month: 7,
        date: 20,
      },
    },
    {
      startDate: {
        year: 2023,
        month: 7,
        date: 22,
      },
      endDate: {
        year: 2023,
        month: 7,
        date: 29,
      },
    },
  ],

이 형태였는데

다시 보니

이렇게 문자열로 들어오는 것이었다.

내가 잘못 봤던 것인가?

내 모든 코드의 로직이 저 형태로 맞춰져 있는데 어떻게 하지?

const convertStringToDateObject = (dateStr: string) => {
  const dateParts = dateStr.split('-');
  return {
    year: parseInt(dateParts[0], 10),
    month: parseInt(dateParts[1], 10),
    date: parseInt(dateParts[2], 10),
  };
};

const convertReservationDates = (reservations: any) => {
  return reservations.map((reservation: any) => {
    return {
      startDate: convertStringToDateObject(reservation.startDate),
      endDate: convertStringToDateObject(reservation.endDate),
    };
  });
};

함수를 만드니 간단해졌다.

물품 검수기간 하루 포함하여 새로고침하니 회색 배경이 지정된다.
와우!!!!!!!!!!!!!!!
아주 감격 ㅠㅠㅠㅠㅠㅠㅠ
물론 POST 요청도 잘된다.

import { useParams } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '../../../common/store/RootStore';
import { setDate } from '../store/CalendarStore';
import { Btn, ButtonWrapper } from '../style';
import axios from 'axios';
import {
  clickLeftArrow,
  clickRightArrow,
} from '../store/MonthlyReservationStore';
import { ACCESS_TOKEN } from '../../Login/constants';

function MonthSwitchBtns() {
  const dispatch = useDispatch();
  const current = useSelector((state: RootState) => state.calendar);
  const { itemId } = useParams<{ itemId: string }>();
  console.log('현재 날짜', current);
  const encryptedAccessToken = localStorage.getItem(ACCESS_TOKEN);
  const accessToken = encryptedAccessToken || '';

  const onClickBack = () => {
    if (current.month > 1) {
      dispatch(setDate({ ...current, month: current.month - 1 }));
    } else {
      dispatch(setDate({ ...current, year: current.year - 1, month: 12 }));
    }
    const getPrevMonthReservation = () => {
      axios
        .get(
          process.env.REACT_APP_API_URL +
            `/api/reservations/products/${itemId}/moreCalendar?date=${
              current.month === 1 ? current.year - 1 : current.year
            }-${
              current.month === 1
                ? 12
                : (current.month - 1).toString().padStart(2, '0')
            }`,
          {
            headers: {
              Authorization: `Bearer ${accessToken}`,
            },
          },
        )
        .then((res) => {
          console.log('지난 달 예약 배열', res.data);

          dispatch(clickLeftArrow(res.data));
        })
        .catch((err) => {
          console.log(err);
        });
    };
    getPrevMonthReservation();
    console.log(
      '왼쪽 버튼 누를 때 요청할 지난 달',
      current.month === 1 ? current.year - 1 : current.year,
      current.month === 1 ? 12 : current.month - 1,
    );
  };

  const onClickNext = () => {
    if (current.month < 12) {
      dispatch(setDate({ ...current, month: current.month + 1 }));
    } else {
      dispatch(setDate({ ...current, year: current.year + 1, month: 1 }));
    }
    const getNextMonthReservation = () => {
      axios
        .get(
          process.env.REACT_APP_API_URL +
            `/api/reservations/products/${itemId}/moreCalendar?date=${
              current.month === 11 || current.month === 12
                ? current.year + 1
                : current.year
            }-${
              current.month === 11 || current.month === 12
                ? (current.month - 10).toString().padStart(2, '0')
                : (current.month + 2).toString().padStart(2, '0')
            }`,
          {
            headers: {
              Authorization: `Bearer ${accessToken}`,
            },
          },
        )
        .then((res) => {
          console.log('다음 달 예약 배열', res.data);

          dispatch(clickRightArrow(res.data));
        })
        .catch((err) => {
          console.log(err);
        });
    };
    getNextMonthReservation();

    console.log(
      '오른쪽 버튼 누를 때 요청할 다음 달',
      current.month === 11 || current.month === 12
        ? current.year + 1
        : current.year,
      current.month === 11 || current.month === 12
        ? current.month - 10
        : current.month + 2,
    );
  };

  return (
    <ButtonWrapper>
      {new Date().getFullYear() === current.year &&
      new Date().getMonth() + 1 === current.month ? (
        <span />
      ) : (
        <Btn onClick={onClickBack}>◀️</Btn>
      )}
      <Btn onClick={onClickNext}>▶️</Btn>
    </ButtonWrapper>
  );
}
export default MonthSwitchBtns;

코드 퀄리티 고려 없이 일단 돌아가라고 외치면서 짠 코드 ㅋㅋㅋㅋㅋㅋ
리팩토링 필수이다.,. 제발....,,,,..


하... 진짜 최고 감격......
눈물 날 것 같음.....

profile
기록에 진심인 개발자 🌿

0개의 댓글