20230225 [미니프로젝트] - 댓글기능

lionloopy·2023년 2월 24일
0

미니프로젝트

목록 보기
2/5
post-thumbnail

처음 해 보는 댓글 기능 trouble shooting

댓글 추가 -> POST
댓글 삭제 -> DELETE

function Comment() {
  const { id } = useParams();

  //댓글 조회
  const [detail, setDetail] = useState({});
  const getComment = async () => {
    const data = await instance.get(`/api/boards/${id}`);
    return data;
  };
  const { data } = useQuery("clean", getComment, {
    onSuccess: (response) => {
      setDetail(response.data.commentList.reverse());
    },
  });
  // const [nickname, setNickname] = useState("");
  const [comment, setComment] = useState("");
  const queryClient = useQueryClient();

  //댓글 추가
  const mutation = useMutation(addComment, {
    onSuccess: () => queryClient.invalidateQueries("clean"),
  });

  const onSubmitHandler = (event) => {
    event.preventDefault();
    const newComment = {
      id: id,
      contents: comment,
    };
    mutation.mutate(newComment);
    alert("댓글 등록 완료!");
    // setNickname("");
    setComment("");
    setDetail([...detail, newComment]);
    console.log(detail);
  };

  //댓글 삭제
  const delMutation = useMutation(deleteComment, {
    onSuccess: () => {
      queryClient.invalidateQueries("clean");
    },
  });
  const commentDeleteHandler = (id) => {
    const message = window.confirm("❗ 댓글을 삭제하시겠습니까?");
    if (message) {
      delMutation.mutate(id);
      setDetail([...detail]);
    } else {
      return;
    }
  };
  const style = {
    width: "20px",
    height: "20px",
  };
  return (
    <div>
      <WrapBox>
        <form onSubmit={onSubmitHandler}>
          <CommentInput
            type="text"
            placeholder="댓글"
            value={comment}
            onChange={(event) => {
              setComment(event.target.value);
            }}
          />
          <Button>등록</Button>
        </form>
      </WrapBox>
      <NewCommentBox>
        {detail.length > 0 &&
          detail.map((item) => {
            return (
              <CommentBox key={item.id}>
                <FaCommentDots style={style} />
                <UserComments>
                  <NameBox>{item.username}</NameBox>
                  <div>{item.contents}</div>
                </UserComments>
                <DButton onClick={() => commentDeleteHandler(item.id)}>
                  삭제
                </DButton>
              </CommentBox>
            );
          })}
      </NewCommentBox>
    </div>
  );
}

export default Comment;

회고

댓글을 등록하고 삭제하는 것 또한 POST / DELETE 방식을 사용하면 되니까 게시글 등록이랑 별로 다를바가 없을거라고 생각했다. 그래서 form과 input을 활용했던 것이었고! 하지만 댓글 한 개 한 개 마다 id 값을 잘 찾아야 되는 것에서 어려움을 겪었다. console로 계속 찍어보고 오류도 마주해보면서 댓글 기능을 구현할 수 있게 되었다 🌱

profile
기록은 담백하게, 성장은 빠르게! 🐘

0개의 댓글

Powered by GraphCDN, the GraphQL CDN