본문 바로가기
👥
총 방문자
📖
0개 이상
총 포스팅
🧑
오늘 방문자 수
📅
0일째
블로그 운영

여러분의 방문을 환영해요! 🎉

다양한 개발 지식을 쉽고 재미있게 알려드리는 블로그가 될게요. 함께 성장해요! 😊

프로젝트/재활용프로젝트

[리액트][재활용 프로젝트] 댓글 crud 구현

by 꽁이꽁설꽁돌 2024. 6. 7.
728x90
반응형

목차

  1. 완성된 모습
  2. crud를 위한 로직 코딩 (usequery이용)
  3. 댓글 수정, 댓글 삭제 토글 버튼 주요 로직

 

완성된 모습

댓글 삭제 토글

 

댓글 수정 토글

 

crud를 위한 로직 코딩 (usequery이용)

시험기간이라 급하게 하다보니 조잡하다..

php
 const { data } = useQuery({   //read 구현
    queryKey: [`comments/${boardId}`],  //쿼리키
    queryFn: ({ signal }) => getData<any>(`boards/${boardId}/comments`, signal),
  });

  const { mutate } = useMutation({   //create 구현
    mutationFn: postComment,
    onSuccess: () => {
      queryClient.invalidateQueries({   //데이터가 즉각 stale 상태(데이터가 만료된 상태)가 되어 refetching 된다.
        queryKey: [`comments/${boardId}`],
      });
    },
    onError: () => {
      console.log('mutate error');
    },
  });
  const api = axios.create({
    baseURL: process.env.REACT_APP_URL,
  });

  const deleteCommentMutation = useMutation({  //delete 구현
    mutationFn: ({
      commentId,
      password,
    }: {
      commentId: number;
      password: string;
    }) =>
      api.delete(`/comments/${commentId}`, {
        data: { password },
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [`comments/${boardId}`],
      });
    },
    onError: () => {
      console.log('delete error');
    },
  });

  const editCommentMutation = useMutation({  //update 구현
    mutationFn: ({
      commentId,
      content,
      password,
    }: {
      commentId: number;
      content: string;
      password: string;
    }) =>
      api.patch(`/comments/${commentId}`, {
        content,
        password,
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [`comments/${boardId}`],
      });
    },
    onError: () => {
      console.log('edit error');
    },
  });

 

댓글 수정, 댓글 삭제 토글 버튼 주요 로직

로직 수정하면 더 예쁘게 리팩토링할 수 있을 것 같은데 시간이;;

typescript
  const [deleteShow, setdeleteShow] = useState<number | null>(null);
  const [editShow, seteditShow] = useState<number | null>(null);


   <div className={styles['comments-body']}>
        {data &&
          data.map((item: any, index: any) => (
            <div key={item.commentId} className={styles['comments-comment']}>
              <div className={styles['comment-username-date']}>
                <div className={styles['comment-date']}>
                  {moment(item.created)
                    .add(9, 'hour')
                    .format('YYYY-MM-DD HH:mm:ss')}
                </div>
              </div>
              <div className={styles['comment-content']}>{item.content}</div>
              <div className={styles['comment-username']}>익명 {index + 1}</div>
              <Button
                type="button"
                onClick={() => handleDelete(item.commentId)}
              >
                삭제
              </Button>
              <Button type="button" onClick={() => handleEdit(item.commentId)}>
                수정
              </Button>
              <hr />
              {deleteShow === item.commentId && (
                <CommentDeleteModal
                  onSubmit={(password: any) =>
                    handleDeleteSubmit(item.commentId, password)
                  }
                />
              )}
              {editShow === item.commentId && (
                <CommentEditModal
                  onSubmit={(password: string, NewComment: string) =>
                    handleEditSubmit(item.commentId, NewComment, password)
                  }
                />
              )}
            </div>
          ))}
      </div>
반응형