[TIL] 230711

이세령·2023년 7월 11일
0

TIL

목록 보기
53/118

코멘트 DB구조 변경

코멘트 추가를 구현중에 질문하였더니 구조를 변경하는게 좋다고 하셔서
바로 post할 수 있도록 다음과 같이 변경했다.

{
      "id": "1",// 코멘트에 대한 id
      "user": // 작성자
      "comment": // 코멘트
      "postid": // 해당 게시글 
    },

이와 같이 구조를 했을 때, depth를 하나 더 깊게 들어갈 필요가 없고 실제 db에서는 index로 찾기 때문에 비효율적이지 않다고 하셨다.
-> 옛날에 MySQL을 배울 때 인덱스 관련 항목이 있던것이 기억난다.

파라미터로 값 찾기
GET /users?name=John

DB 구조 변경에 따른 코드 수정

studytodo.js
통신하는 부분에서 postid로 찾아올 수 있도록 변경해준다.

const getComments = async (id) => {
  const response = await axios.get(
    `${process.env.REACT_APP_SERVER_URL}/comments/?postid=${id}`
  );
  console.log("comments res", response);
  return response.data;
};

불러오는 값들을 .userComments로 배열을 가져왔던 것을 data로 받을 수 있게 변경해주었다.

댓글 추가하기

comments에 바로 post 동작을 실행해주면 동작한다.
studyTodo.js

const addnewComment = async (newComment) => {
  const response = await axios.post(
    `${process.env.REACT_APP_SERVER_URL}/comments`,
    newComment
  );
  console.log("comments add res", response);
};

Inputcomment.jsx

 // 코멘트 추가 이벤트
  const postCommentMutation = useMutation(addnewComment, {
    onSuccess: () => {
      queryClient.invalidateQueries(`${param.id}Comments`);
    },
  });

  const handleSubmitButtonClick = (event) => {
    // 유효성 검사
    if (!inputUser || !inputComment) {
      return alert("작성자 또는 내용이 입력되지 않았습니다!");
    }

    const newComment = {
      id: shortid,
      user: inputUser,
      comment: inputComment,
      postid: param.id,
    };
    // post
    postCommentMutation.mutate(newComment);

    setInputUser("");
    setInputComment("");
    alert("저장되었습니다!");
  };

댓글을 작성하면 댓글 추가가 되는 것을 볼 수 있다!

댓글 삭제

  • Axios
const deleteComment = async (id) => {
  const response = await axios.delete(
    `${process.env.REACT_APP_SERVER_URL}/comments/${id}`
  );
  console.log("comment delete", response);
};
  • 버튼 동작
 const queryClient = useQueryClient();
 const deleteCommentMutation = useMutation(deleteComment, {
    onSuccess: () => {
      queryClient.invalidateQueries(`${codata.postid}Comments`);
      console.log("comment Delete 성공");
    },
  });

  const deleteCommentHandler = () => {

    if (window.confirm("이 코멘트를 삭제하시겠습니까??")) {
      //확인
      deleteCommentMutation.mutate(codata.id);
      alert("삭제되었습니다!");
    } else {
      return false;
    }
  };

Giltch json-server 배포하기

  1. 서버를 위한 repository를 만든다
    https://github.com/kitloong/json-server-vercel

  2. db.json 수정하기
    초기값으로 설정하고 싶은 코드로 변경해준다.
    Glitch에서 변경 가능하니 배포 후 해주어도 된다.

  3. new project
    새 프로젝트 만들기를 눌러서 서버를 배포해준다.
    repository url을 입력하면 된다.

  4. 서버 적용하기
    localhost 대신
    share -> Live site의 주소로 변경해준다.

  5. vercel에 배포하기
    내가 만든 repository를 vercel에 배포하고, 환경변수를 작성해준다.

새로 알게된 문법

null 병합 연산자(nullish coalescing operator)
a ?? b
a가 null도 아니고 undefined도 아니면 a
그 외일 때 b

이번 과제를 수행하면서 DB를 어떻게 설게하느냐에 따라 코딩의 난이도가 바뀌는 것을 느낄 수 있었다.
react-query를 사용하여 통신, 상태관리를 한다면 redux는 어디에 사용되는지 궁금하고 고민해보았는데, 로그인 상태를 전역적으로 관리해주면 버튼유무 등을 관리할 수 있을 것 같다는 생각이 들었다.
다음 과제인 로그인/로그아웃을 구현하면서 적용해봐야겠다.

profile
https://github.com/Hediar?tab=repositories

0개의 댓글