BE/스프링 부트 3

19장 웹 페이지에서 댓글 삭제하기

이제하네 2024. 1. 6. 18:18

댓글 삭제 버튼 추가하기

  1. _list.mustache 파일을 열고 수정 버튼 아래에 <button> 태그로 삭제 버튼을 만듬
_list.mustache

			<button type="button"
            		class="btn btn-sm btn-outline-primary"
            		data-bs-toggle="modal"
            		data-bs-target="#comment-edit-modal"
            		data-bs-id="{{id}}" 
            		data-bs-nickname="{{nickname}}"
            		data-bs-body="{{body}}"
            		data-bs-article-id="{{articleId}}">수정</button> 
			<!-- 댓글 삭제 버튼 -->
			<button type="button" 
            class="btn btn-sm btn-outline-danger comment-delete-btn">삭제</button>

 

자바스크립트로 댓글 삭제하기

  • 클릭 이벤트 처리하기
    1. _list.mustache 파일의 맨 아래 빈 공간에 <script> 태그를 작성하고 그 안을 중괄호({})로 블록을 잡음
    2. [삭제] 버튼을 document.querySelector(".comment-delete-btn") 으로 받아와서 commentDeleteBtn 변수에 저장
    3. addEventListener()로 삭제 버튼의 클릭 이벤트를 감지
    4. 하지만 querySelector로 하면 첫번째 버튼만 클릭 되므로  querySelectorAll() 메서드로 모든 [삭제] 버튼을 선택하고 변수명도 끝에 s를 붙여 commentDeleteBtns로 수정
    5. 반복 처리를 위해 forEach() 메서드를 사용
      1. forEach() 메서드로 commentDeleteBtns에서 버튼을 하나씩 꺼내 반복하고 각 버튼은 btn이라는 매개변수로 받아 화살표(=>)함수를 실행
        • 화살표 함수 (=>) 형식
          () => {...} // 매개변수가 없는 경우
          x => {...} 또는 (x) => {...} // 매개변수가 1개인 경우
          (x, y) => {...} // 매개변수가 여러 개인 경우
    6. 삭제 버튼을 클릭했을 때 해당 댓글의 id를 가져오기 위해 삭제 버튼의 데이터 속성으로 data-comment-id="{{id}}"를 추가
    7. btn 에 클릭 이벤트가 발생했을 때 이벤트와 관련한 버튼 요소 가져옴
      1. 화살표 함수의 매개변수로 event 객체를 받아옴
      2. event.target 으로 이벤트를 발생시킨 요소를 commentDeleteBtn에 저장
      3. commentDeleteBtn에서 data-comment-id 속성 값을 가져와 commentId 변수에 저장 
  _list.mustache
  
 	<!-- 댓글 삭제 버튼 -->
	<button type="button" class="btn btn-sm btn-outline-danger comment-delete-btn"
	data-comment-id="{{id}}">삭제</button>
    
    
    
    <script>
{
	//삭제 버튼 선택
	const commentDeleteBtns = document.querySelectorAll(".comment-delete-btn");
	// 삭제 버튼 이벤트 처리
		commentDeleteBtns.forEach(btn => {         // 삭제 버튼 수만큼 반복
			btn.addEventListener("click", (event) => { 
		   		// 이벤트 발생 요소 선택
		    	const commentDeleteBtn = event.target; 
		    	// 삭제 댓글 id 가져오기
		    	const commentId = commentDeleteBtn.getAttribute("data-comment-id");
	    });
	});
}
</script>

 

  • 자바스크립트로 REST API 호출하고 응답 처리하기
    1. url 변수에 API 주소를 저장
      • 여기서는 백틱(')을 사용해서 API 주소를 저장
        • 백틱 : 문자열을 정의하는 방법으로 백틱을 사용하면 ${} 문법으로 문자열에 변수 또는 식을 넣을수 있음
        • 형식 :
          `삭제 버튼 클릭: ${commentId}번 댓글`      // 백틱(`) 문자열에 변수 삽입
          "삭제 버튼 클릭: " + commentId + "번 댓글" // 큰따옴표 문자열을 덧셈 연결 ​
    2. fetch() 함수 작성
_list.mustache

<script>
{
	//삭제 버튼 선택
	const commentDeleteBtns = document.querySelectorAll(".comment-delete-btn");
	// 삭제 버튼 이벤트 처리
		commentDeleteBtns.forEach(btn => {         // 삭제 버튼 수만큼 반복
			btn.addEventListener("click", (event) => { 
		   		// 이벤트 발생 요소 선택
		    	const commentDeleteBtn = event.target; 
		    	// 삭제 댓글 id 가져오기
		    	const commentId = commentDeleteBtn.getAttribute("data-comment-id");
		    	const url = `/api/comments/${commentId}`;  // 백틱을 사용
		    	fetch(url, { 
		    		  method: "DELETE"
		    		}).then(response => {  // 응답 처리(실패 시, 성공 시)
		    		  // 댓글 삭제 실패 처리
		    		  if (!response.ok) { 
		    		    alert("댓글 삭제 실패..!");
		    		    return;
		    		  }
		    		  // 삭제 성공 시 댓글을 화면에서 지우고 메시지 창 띄우기
		    		  const target = document.querySelector(`#comments-${commentId}`);
		    		  target.remove();
		    		  const msg = `${commentId}번 댓글을 삭제했습니다.`;
		    		  alert(msg);
		    		  // 현재 페이지 새로 고침
		    		  window.location.reload();
		    		});
	    });
	});
}
</script>

댓글 삭제 잘됨