본문 바로가기

TIL

상세페이지 - 각 댓글별 수정 모드

🚨 문제

현재 진행중인 최종프로젝트의 댓글 기능 구현 중 입력된 댓글의 수정 버튼을 눌렀을때, 개별 댓글이 아니라 댓글 전체가 수정모드가 된다.

 

기존코드

const [commentItem, setCommentItem] = useState("");
const [edited, setEdited] = useState(false);

// 편집모드
  const handleNicknameEdit = () => {
    setEdited(!edited);
  };

        {commentList?.map((comment) => (
          <div key={comment.comment_id}>
            {edited ? (
              <>
                (
                <form
                  onSubmit={(e) => {
                    e.preventDefault();
                    updateComment({
                      commentId: comment.comment_id,
                      content: updateCommentItem,
                    });
                    handleNicknameEdit();
                  }}
                >
                  <input
                    value={updateCommentItem}
                    onChange={(e) => setUpdateCommentItem(e.target.value)}
                    placeholder={comment.comment_contents}
                  />
                  <button>완료</button>
                </form>
                )
              </>
            ) : (
              <div>
                <span>{user?.name}</span>
                <span>{comment.comment_createtime.slice(0, 10)}</span>
                <button onClick={handleNicknameEdit}>수정</button>
                <button onClick={() => deleteComment(comment.comment_id)}>
                  삭제
                </button>
                <p>{comment.comment_contents}</p>
              </div>
            )}

 

원인

edited라는 상태가 하나만 존재하기 때문에 어느 댓글이든 수정 버튼을 누르면 모든 댓글이 edited 로 변경 되었던 것!

 

 

해결방법

edited 상태를 객체로 바꾸어 각 댓글 수정 상태를 별도로 관리해서 해결하였다.

// 초기값을 {} 로 변경하고 타입 키를 인덱스 시그니처로 지정
const [edited, setEdited] = useState<{ [key: string]: boolean }>({});

  // 댓글 수정 토글 변경
  const toggleEditMode = (commentId: string) => {
    setEdited((prev) => ({
      ...prev,
      [commentId]: !prev[commentId],
    }));
  };
  
  {commentList?.map((comment) => (
          <div key={comment.comment_id}>
            {edited[comment.comment_id] ? (
              <form
                onSubmit={(e) => {
                  e.preventDefault();
                  updateComment({
                    commentId: comment.comment_id,
                    content: updateCommentItem,
                  });
                  toggleEditMode(comment.comment_id);
                }}
              >
                <input
                  value={updateCommentItem}
                  onChange={(e) => setUpdateCommentItem(e.target.value)}
                  placeholder={comment.comment_contents}
                />
                <button>완료</button>
              </form>
            ) : (
              <div>
                <span>{user?.name}</span>
                <span>{comment.comment_createtime.slice(0, 10)}</span>
                <button onClick={() => toggleEditMode(comment.comment_id)}>
                  수정
                </button>
                <button onClick={() => deleteComment(comment.comment_id)}>
                  삭제
                </button>
                <p>{comment.comment_contents}</p>
              </div>
            )}

 

각 댓글 마다 개별적으로 수정모드 적용이 잘 된다.

 

 

🧐 느낀점

이전에 토글형식? 비슷하게 편집모드 만들어 적용해서 닉네임 변경 기능을 구현했던 로직처럼 적용을 했었는데 그때의 경우 변경할 값이 하나여서 문제없이 동작을 했었다. 그치만 오늘 작업한 댓글 수정의 경우 편집모드가 각 댓글별로 별도로 적용이 되어야 해서 조금 헤맸지만 다음번 비슷한 기능을 구현하게 된다면 수정 상태를 별도로 관리하는 방법을 생각해낼 수 있을 것 같아서 좋은 경험이었다.

'TIL' 카테고리의 다른 글

console.error() 와 throw error 의 차이  (1) 2024.10.27
Tanstack Query - querykey  (0) 2024.10.25
Tanstack Query - useMutation 오류  (0) 2024.10.23
[TIL] 모의면접 ①  (1) 2024.10.22
최종 프로젝트 시작  (0) 2024.10.18