[TIL] 팀 프로젝트 프론트엔드 게시글 수정/ 삭제 완료

김민재·2023년 11월 26일
0

TIL

목록 보기
62/172
post-thumbnail
  • 게시글 삭제

상세 게시글에 들어가면 게시글 삭제 버튼과 수정 버튼을 만들어뒀다. 삭제를 누르면

뜨고 새로고침을 해줘서 원래 페이지로 돌아가게 한다. 그러면 삭제된 건 사라진다.

  • 게시글 수정

상세 게시글에서 수정 버튼을 누르면 요런 모달이 뜨는데, 제목과 내용과 장르 VALUE를 새롭게 다시 넣어준다.

확인 버튼을 누르면 업데이트가 되고, 새로고침을 해준다.

게시글 수정 코드

 // 게시글 수정
  const post_edit_btn = document.createElement('button');
  post_edit_btn.classList.add('post_edit_btn');
  post_edit_btn.innerHTML = '수정';
  // 게시글 수정 버튼 클릭 시 함수 실행
  post_edit_btn.addEventListener('click', async () => {
    const postId = post.post.postId;

    // 업데이트 포스트 모달
    post_modal.innerHTML = `
      <label for="update_title">제목:</label>
      <input type="text" id="update_title" value="${title}">
      <br>
      <label for="update_body">내용:</label>
      <input id="update_body" value="${body}"></input>
      <br>
      <label for="update_genre">장르:</label>
      <select id="update_genre"></select>
      <br>
      <button id="confirm_update">확인</button>
      <button id="cancel_update">취소</button>
    `;

    posts_container.appendChild(post_modal);

    // 드랍메뉴 updata_genre에 넣어주기
    const category_data = await fetchCategory();
    const update_genre_dropdown = document.getElementById('update_genre');
    category_data.category.forEach((genre) => {
      const option = document.createElement('option');
      option.value = genre;
      option.textContent = genre;
      update_genre_dropdown.appendChild(option);
    });

    // 수정 확인 누를 시 업데이트api를 받고 업데이트 해준다.
    const update_confirm_btn = document.getElementById('confirm_update');
    update_confirm_btn.addEventListener('click', async () => {
      const update_title = document.getElementById('update_title').value;
      const update_body = document.getElementById('update_body').value;
      const update_genre = document.getElementById('update_genre').value;

      if (
        update_title === null ||
        update_body === null ||
        update_genre === null
      ) {
        return alert('빈칸을 입력하세요.');
      }

      const updatedPost = {
        title: update_title,
        body: update_body,
        genre: update_genre,
      };

      const response = await fetch(
        `http://localhost:3000/api/auth/post/${postId}`,
        {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(updatedPost),
        },
      );
      const responseData = await response.json();
      alert(responseData.message);
      window.location.reload();
    });
  });

게시글 삭제 코드

  // 게시글 삭제
  const post_delete_btn = document.createElement('button');
  post_delete_btn.classList.add('post_delete_btn');
  post_delete_btn.innerHTML = '삭제';
  // 게시글 삭제 api와 버튼 클릭 시 삭제
  post_delete_btn.addEventListener('click', async () => {
    const postId = post.post.postId;
    const response = await fetch(
      `http://localhost:3000/api/auth/post/${postId}`,
      {
        method: 'DELETE',
      },
    );
    const responseData = await response.json();
    alert(responseData.message);
    window.location.reload();
  });

이런저런 부족한 부분들이 많지만.. 약 5일 만에 주구장창 계속 해서 이런 기본적인 기능들을 만들어냈다.
내일인 월요일일에 제출이다. 팀원 것까지 같이 하느냐고 너무 벅찼다. 그래서 CSS를 건들지 못했다. 지금이라도 조금씩 건드려봐야겠다.

// 추가 수정으로
다른 사람 게시글을 클릭하면 수정/삭제 버튼을 숨겼다. 내 게시글에서만 확인 가능하다.

  • 다른 사람 게시물

  • 내 게시물

profile
개발 경험치 쌓는 곳

0개의 댓글

관련 채용 정보