미니프로젝트
오늘은 두가지 할 일이 있었다.
하나는 index 중복의 오류 이고 하나는 코멘트를 삭제하는 버튼을 만드는 것이었다.
commentBackgroundColor
index는 생각지도 못한 방법으로 해결되었다.
그동안 forEach라는 메서드가 array에 대한 element와 이를 처리할 함수만 매개변수로 받는다고 생각했는데 그것이 아니었다.
index 또한 매개변수로 받게 된다.
const minseok_comment_list = []
async function get_minseok() {
const q = query(collection(db, "minseok"), orderBy("date"))
const querySnapshot = await getDocs(q)
querySnapshot.forEach((doc) => {
const row = doc.data();
const comment = row['comment'];
minseok_comment_list.push(comment)
})
minseok_comment_list.forEach((a, index) => {
if (index % 2 === 0) {
const temp_html = `<p class='comment_background_white'>${a}</p>`;
$('#commented_minseok').prepend(temp_html);
} else {
const temp_html = `<p class='comment_background_gray'>${a}</p>`;
$('#commented_minseok').prepend(temp_html);
}
})
}
get_minseok()
indexof 를 통해 list내 element의 index를 찾지않고
forEach를 사용할때 바로 index를 구분하니 중복이 없이 원하는대로 표현되었다.
그리고 저번주 튜터님의 조언을 들을때 제안해주셨던 삼항연산자로 표현하는것도 도전해 보았다.
const minseok_comment_list = []
async function get_minseok() {
const q = query(collection(db, "minseok"), orderBy("date"))
const querySnapshot = await getDocs(q)
querySnapshot.forEach((doc) => {
const row = doc.data();
const comment = row['comment'];
minseok_comment_list.push(comment)
})
minseok_comment_list.forEach((a, index) => {
const commentColor = index % 2 == 0 ? `<p class='comment_background_white'>${a}</p>` : `<p class='comment_background_gray'>${a}</p>`;
$('#commented_minseok').prepend(commentColor);
})
}
get_minseok()
삼항연산자를 사용하니 확실히 깔끔하게 정리되었다.
삼항연산자를 이해하는과정에서 변수에 함수를 담을 수 있고 그 변수명을 통해 함수를 실행 시킬 수 도 있다는 것을 배웠다.
commentDelete
내가 원하던것을 구현하고나서 정신을 차려보니 삭제버튼이 구현 되어있지 않았다.
앞서 노마드코더의 바닐라js강의를 들은적이 있어 자신감을가지고 도전해 보았다.
import { doc, deleteDoc } from "firebase/firestore";
await deleteDoc(doc(db, "cities", "DC"));
firebase 공식 api문서에 따르길 데이터를 삭제하기 위해서는 doc와 deleteDoc을 import하여야 했다.
그 후 삭제버튼에 click을 연결하고 click을 통해 DC(문서의 id값)을 찾아 해당 cities(collection이름)에 deleteDoc을 요청하면 되는 것 이었다.
//민석 db삭제
async function minseokHandleDeleteBtn(e) {
const goodbye_comment = e.target.parentElement.id;
await deleteDoc(doc(db, "comments_minseok", goodbye_comment));
location.reload();
}
//민석 db가져오기
async function get_comments_minseok() {
const q = query(collection(db, "comments_minseok"), orderBy("date"));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
const row = doc.data();
const comment = row["comment"];
const teml_html = `<p class = 'commentColor'id='${doc.id}'>${comment}<img src="./img/delete_btn.png" class='delete_btn minseok_delete_btn'></p>`;
$("#commented_minseok").prepend(teml_html);
});
const delete_btns = document.querySelectorAll(".minseok_delete_btn");
delete_btns.forEach((a) => {
a.addEventListener("click", minseokHandleDeleteBtn);
});
}
get_comments_minseok();
query를 q에 담아 gerDocs를 querySnapshot에 저장하였고 querySnapshot을 forEach메서드를 통해 출력할 comment를 p태그로 감싸 prepend시키는 과정에서 p태그의 class에 jquery를 통하여 doc의 id값을 저장하였다.
이를 통해 각 comment들은 저장되어있는 문서의 id값을 담고 있었기에 addEventListenr를 통해 click으로 접근하여 firestore에 comment 삭제를 요청 할 수 있었다.
이 과정중 commentBackgroundColor를 포기하여야 되어 아쉬웠지만 같은 조원분이 css를 이용하여 commentBackgroundColor를 다시 구현해주었다 :)