JavaScript
[TIL] 내배캠_영화소개페이지(3)_리뷰 수정 기능 구현하기
어느새벽
2024. 5. 10. 20:31
localStorage.getItem()으로 리뷰 작성했던 key를 가져온다.
각 영화마다 리뷰를 달 수 있도록 구별하기 위해 key에 영화 api의 id를 넣어둔 상태이므로
해당하는 영화의 id값과 같다면 filter()로 반환한다.
그리고 수정하고자 하는 리뷰의 작성시간이 같다면 findIndex()로 반환하고
(한 영화에 댓글이 많을 때 비밀번호가 같을 수도 있으므로 수정하고자 하는 댓글의 time값을 비교했다.)
조건문으로 비밀번호 일치 여부에 따라 수정 처리 해준다.
그후 setItem()으로 저장한 후 다시 loadComments()하여 출력한다.
function editComment(index) {
const comments = JSON.parse(localStorage.getItem("comments") || "[]");
const commentFilter = comments.filter(
(comment) => comment.movieId === searchParam("id")
);
const commentToEdit = commentFilter[index];
const originalIndex = comments.findIndex(
(c) => c.time === commentToEdit.time
);
const inputPassword = prompt("비밀번호를 입력하세요.");
if (inputPassword === null) {
alert("취소되었습니다.");
return;
}
if (inputPassword !== commentToEdit.password) {
alert("비밀번호가 일치하지 않습니다.");
return;
}
const newComment = prompt(
"새로운 댓글 내용을 입력하세요.",
commentToEdit.comment
);
if (newComment === null) {
alert("취소되었습니다.");
return;
}
if (newComment.trim() === "") {
alert("수정할 내용을 입력해주세요.");
return;
}
comments[originalIndex].comment = newComment.trim();
localStorage.setItem("comments", JSON.stringify(comments));
loadComments();
alert("댓글이 수정되었습니다.");
}
반응형