[토이] 개발 - 일기작성

최정윤·2023년 8월 31일
0

에반

목록 보기
10/12

일기 제작 참고 블로그

감정일기 관련 강의

rest api를 활용한 서버 통신 강의

rest api로 일기 데이터 불러오기

http://13.209.16.226:8080/api/auth/emailCheck
{
"check" : "use3311@email.com"
}

http://13.209.16.226:8080/api/auth/signIn
{
"userEmail" : "use3311@email.com",
"userPassword" : "user1password"
}

http://13.209.16.226:8080/api/diary/view?addDate=2023-01-01
{
"diaryDetail" : "오늘은 알고리즘 스터디를 했다. 너무 재밌었다.",
"addDate" : "2023-01-01"
}

일기 추가 페이지

입력창에 어떠한 값을 입력해도

ERROR
Cannot read properties of undefined (reading 'refs')
TypeError: Cannot read properties of undefined (reading 'refs')

이와 같은 에러가 발생한다.

npm update --force

프로젝트에서 사용하는 모든 패키지를 제거한 후 다시 설치하는 과정

rm -rf node_modules
npm install --force

일기 작성 페이지

calendar.js 0904 코드백업

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import {Link, useNavigate} from 'react-router-dom';
import moment from 'moment';
import 'moment/locale/ko';
import styled from 'styled-components';
import {
  CalHeader,
  LogoImg,
  SetImg,
  ButtonWrapper,
  CalendarWrapper,
  Header,
  DateContainer,
  Weekend,
  Dow,
} from '../component_css/calendar_style';
import {
  MdChevronLeft,
  MdChevronRight,
  MdDehaze,
  MdCheck,
  MdDoneAll,
  MdEdit
} from 'react-icons/md';
// import { useDispatch, useSelector } from 'react-redux';
// import {
//   readSchedule,
//   setIsFilter,
//   openEditPopup
// } from './schedule';
import Day from './day';
import EditSchedule from './editschedule';


// const Calendar = ({ history }) => {
  const Calendar = () => {
  // const { thisMonth, isOpenEditPopup, isFilter } = useSelector(
  //   (state) => state.schedule
  // );
  // const { thisMonth, isOpenEditPopup, isFilter } = useSelector(
  //   state => state.someReducer
  // );
  const [isOpenEditPopup, setIsOpenEditPopup] = useState(false);
  // Function to open the popup
  const openPopup = () => {
    setIsOpenEditPopup(true);
  };

  // Function to close the popup
  const closePopup = () => {
    setIsOpenEditPopup(false);
  };

  const [isEditPopupOpen, setEditPopupOpen] = useState(false);

  const handleButtonClick = () => {
    setEditPopupOpen(false); // 상태 변경 함수 호출
  };

  // Dummy reducer
  const thisMonth = [
    { id: 1, date: "20230901", title: "Event1", description: "This is event1" },
    { id: 2, date: "20230902", title: "Event2", description: "This is event2" },
  ];
  
  // const isOpenEditPopup = false;
  
  const isFilter = false;

  const [current, setCurrent] = useState(moment());
  const [schedules, setSchedules] = useState(thisMonth);

  // ============================ 필터 관련 이벤트 ============================
  // useEffect(() => {
  //   const startDay = current.clone().startOf('month').format('YYYYMMDD');
  //   const endDay = current.clone().endOf('month').format('YYYYMMDD');

  //   // Filter the schedules based on the current month
  //   const filteredSchedules = thisMonth.filter(schedule =>
  //     schedule.startDay >= startDay && schedule.endDay <= endDay
  //   );

  //   setSchedules(filteredSchedules);
    
  //  }, [current, isOpenEditPopup, isFilter]);
  
  // const dispatch = useDispatch();
  // useEffect(() => {
  //   const startDay = current.clone().startOf('month').format('YYYYMMDD');
  //   const endDay = current.clone().endOf('month').format('YYYYMMDD');
  //   // dispatch(readSchedule({ startDay, endDay }));
  // }, [current, dispatch, isOpenEditPopup, isFilter]);

  const movePrevMonth = () => {
    setCurrent(current.clone().subtract(1, 'month'));
  };

  const moveNextMonth = () => {
    setCurrent(current.clone().add(1, 'month'));
  };
  const navigate = useNavigate();
  const goToAddSchedule = () => {
    // history.push('/addSchedule');
    navigate('/addSchedule');
  };
  const generate = () => {
    // 일년은 52주
    const startWeek = current.clone().startOf('month').week();
    const endWeek =
      current.clone().endOf('month').week() === 1
        ? 53
        : current.clone().endOf('month').week();

    // 날짜
    let calendar = [];

    for (let w = startWeek; w <= endWeek; w++) {
      calendar.push(
        <Weekend key={w}>
          {Array(7)
            .fill(0)
            .map((n, idx) => {
              const noFormatDate = current
                .clone()
                .startOf('year')
                .week(w)
                .startOf('week')
                .add(idx, 'day');

              const day = noFormatDate.format('D');
              const fullDate = noFormatDate.format('l').replaceAll('.', '');
              const isToday =
                noFormatDate.format('YYYYMMDD') === moment().format('YYYYMMDD')
                  ? 'today'
                  : '';
              const isGrayed =
                noFormatDate.format('MM') === current.format('MM')
                  ? ''
                  : 'grayed';

              const currentSch = thisMonth.filter((s) => {
                return s.date === fullDate;
              });

              const dateInfo = { day, fullDate, dow: idx, currentSch };
              return (
                <Day
                  key={n + idx}
                  dateInfo={dateInfo}
                  className={`${isGrayed} ${isToday}`}
                />
              );
            })}
        </Weekend>
      );
    }
    return calendar;
  };

  const onFilter = (isFilter) => {
    // dispatch(setIsFilter(isFilter));
  };

  // // ======================================================== rest api 받아오기 ========================================================
  // const [data, setData] = useState(null);
  
  // useEffect(() => {
  //   const checkEmail = async () => {
  //     const payload = { check: "use3311@email.com" };
      
  //     try {
  //       const response = await axios.post('http://13.209.16.226:8080/api/auth/emailCheck', payload);
  //       console.log(response.data); 
  //       setData(response.data); // 응답 데이터를 state 변수에 저장
  //     } catch (error) {
  //       console.error(error);
  //     }
  //   };
  //   checkEmail();
  // }, []); // 빈 배열을 dependency로 전달하여 마운트 시 한 번만 실행되도록 함
  // console.log(data);

  return (
    <div>
      <CalHeader>
        <LogoImg src={'img/logo.png'}></LogoImg>
        <SetImg src={'img/setting.png'}></SetImg>
      </CalHeader>
      <CalendarWrapper>
          {/* Button to open the popup */}
        {/* <button onClick={openPopup}>Open Popup</button> */}

        {/* Button to close the popup (this could be inside EditSchedule component) */}
        {/* {isOpenEditPopup && <button onClick={closePopup}>Close Popup</button>} */}
        {/* {isOpenEditPopup && <EditSchedule />} */}
        {isOpenEditPopup && (
        <ModalWrapper>
          <ModalOverlay onClick={openPopup} />
          <ModalContent>
            <EditSchedule onClose={openPopup} />
          </ModalContent>
        </ModalWrapper>
      )}
        <Header>
          <MdChevronLeft
            className="dir"
            onClick={movePrevMonth}
          ></MdChevronLeft>
          <span>{current.format('MMMM')}</span>
          <MdChevronRight
            className="dir"
            onClick={moveNextMonth}
          ></MdChevronRight>
        </Header>
        <DateContainer>
          <Weekend className="row">
            <Dow color="#ff4b4b">
              <span>S</span>
            </Dow>
            <Dow>
              <span>M</span>
            </Dow>
            <Dow>
              <span>T</span>
            </Dow>
            <Dow>
              <span>W</span>
            </Dow>
            <Dow>
              <span>T</span>
            </Dow>
            <Dow>
              <span>F</span>
            </Dow>
            <Dow color="#4b87ff">
              <span>S</span>
            </Dow>
          </Weekend>
          {generate()}
        </DateContainer>
      </CalendarWrapper>
      <ButtonWrapper onClick={handleButtonClick}
        // onClick={() => {
          // dispatch(openEditPopup(false));
        // }}
      >
        {/* {isFilter ? (
          <MdCheck
            onClick={() => onFilter(false)}
            className={'filterBtn subBtn'}
          />
        ) : (
          <MdDoneAll
            onClick={() => onFilter(true)}
            className={'filterBtn subBtn'}
          />
        )} */}
        <MdEdit onClick={goToAddSchedule} className={'writeBtn subBtn'} />
        <MdDehaze className={'menuBtn'} />
      </ButtonWrapper>
    </div>
  );
};

const ModalWrapper = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  width:100%;
   height:100%;
   display:flex;
   justify-content:center;
   align-items:center;
`;

const ModalOverlay = styled.div`
   position:absolute;
   top:0px;
   left:0px; 
   width:100%;
   height:100%;
   background-color:black; 
   opacity:.5; 
`;

const ModalContent = styled.div`
    background-color:white; 
    padding :20px; 
`;

export default Calendar;

addschedule.js 0904 코드백업

import React, { useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import styled from 'styled-components';
import { MdChevronLeft } from 'react-icons/md';
import Datepicker from './datepicker';
import { Button, TextField, makeStyles } from '@material-ui/core';
// import { useDispatch } from 'react-redux';
// import { createSchedule } from './schedule';
import moment from 'moment';
import {
  CalHeader,
  LogoImg,
  SetImg,
} from '../component_css/calendar_style';

// const AddSchedule = ({ history }) => {
  const AddSchedule = () => {
    const [date, setDate] = useState(
      moment().format().split(':')[0] + ':' + moment().format().split(':')[1]
    );
    console.log(date);
    const [title, setTitle] = useState('');
    console.log(title);
    // const [description, setDescription] = useState('');
    const [titleError, setTitleError] = useState(false);
    // const dispatch = useDispatch();

    // Initialize the references here
    const inputTitle = useRef(null);
    const inputDescription = useRef(null);

    const useStyles = makeStyles((theme) => ({
      textField: {
        marginLeft: theme.spacing(1),
        marginRight: theme.spacing(1),
        width: 250,
        textAlign: 'center'
      },
      button: {
        width: '250px',
        backgroundColor: 'skyblue',
        color: 'white'
      }
    }));

    const classes = useStyles();
    const navigate = useNavigate();
    const onAddSchedule = () => {
      if (checkValid()) {
        const yyyymmdd = date.split('T')[0].replaceAll('-', '');
        const time = date.split('T')[1].replaceAll(':', '');
        // const data = { date: yyyymmdd, time, title, description };
        const data = { date: yyyymmdd, time, title };

        // dispatch(createSchedule(data));

        // history.push('/');
        navigate('/');
      }
    };

    const checkValid = () => {
      if (title.length === 0 || title.trim().length === 0) {
        setTitleError(true);
        return false;
      }

      return true;
    };
    return (
      <Wrapper>
        <CalHeader>
          <LogoImg src={'img/logo.png'}></LogoImg>
        </CalHeader>
        <Header>
          <MdChevronLeft
            onClick={() => {
              // history.goBack();
              // navigate(-1);
              navigate('/');
            }}
          />
          일기 작성 &nbsp;&nbsp;&nbsp;
          <i />
        </Header>
        <Body>
          <Datepicker setDate={setDate} date={date} />
          {/* <select>
            <option value="행복">행복</option>
            <option value="중립">중립</option>
            <option value="슬픔">슬픔</option>
            <option value="분노">분노</option>
            <option value="놀람">놀람</option>
            <option value="싫음">싫음</option>
            <option value="두려움">두려움</option>
          </select> */}
             {/* <TextField
            // id="standard-basic"
            // label="어떤 일정이 있나요?"
            // error={titleError}
            // className={classes.textField}
            // onChange={(e) => {
            //   setTitle(e.target.value);
            //   setTitleError(false); // Reset the error state when user starts typing.
            // }}
            // inputRef={inputTitle} // Use the ref here.
          />*/}
          <TextField
            id="outlined-multiline-static"
            label="간단 메모"
            multiline
            rows={4}
            className={classes.textField}
            variant="outlined"
            // onChange={(e) => {
            //   setDescription(e.target.value);
            // }}
            // inputRef={inputDescription} // Use the ref here.
          />
          <Button
            className={classes.button}
            variant="contained"
            // onClick={onAddSchedule}
            onClick={() => {
              // history.goBack();
              // navigate(-1);
              navigate('/calendar');
            }}
          >
            + ADD
          </Button>
        </Body>
      </Wrapper>
    );
};

const Wrapper = styled.div`
  padding: 0 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
`;

const Header = styled.div`
  background-color: white;
  height: 7vh;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 3px;
  font-size: 1.5em;

  & * {
    color: #cccccc;
    cursor: pointer;
  }

  /* Mobile Device */
  @media screen and (max-width: 767px) {
    width: 100vw;
  }

  /* Tablet Device */
  @media screen and (min-width: 768px) and (max-width: 991px) {
    width: 100vw;
  }

  /* Desktop Device */
  @media screen and (min-width: 992px) {
    width: 30vw;
  }
`;

const Body = styled.div`
  background-color: white;
  padding-top: 6vh;
  height: 50vh;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;

  /* Mobile Device */
  @media screen and (max-width: 767px) {
    width: 100vw;
  }

  /* Tablet Device */
  @media screen and (min-width: 768px) and (max-width: 991px) {
    width: 100vw;
  }

  /* Desktop Device */
  @media screen and (min-width: 992px) {
    width: 30vw;
  }
`;
export default AddSchedule;
profile
개발 기록장

0개의 댓글