์ฐ๊ด ์ฝ๋ฉ ๋งํฌ -
๋๊ธ์ด firestore์ add์ get์ ์๋์์ง๋ง, addํ์๋ง์ ํ์ด์ง์ ๋ฐ์๋์ง ๋ชปํ๋ค.
๊ทธ๋์ ๋ฐ๋ก๋ฐ๋ก ์ถ๊ฐ๋๋ฉด ์ข๊ฒ ๋ค๊ณ ์๊ฐํ๋ค.
์ด๋ ์ฌ์ฉ ๊ฐ๋ฅํ ๊ฒ์ด ๋ฐ๋ก Firestore์ ์ค์๊ฐ ๋ฆฌ์ค๋ onSnapshot() ์ด๋ค!
๊ธฐ์กด js ์ฝ๋๋ฅผ ๋ฆฌํฉํ ๋ง ํด๋ณด์
๋๋ commenting์ด๋ผ๋ ์ฝ๋์ ์์ ๋ฐ์ดํฐ๋ฅผ ์ ์ฅํ๊ณ ๊ฐ์ ธ์์๋ค.
$(document).ready(async function () {
let docs = await getDocs(collection(db, "commenting"));
docs.forEach((doc) => {
let commentData = doc.data();
let temp_html = `<div class="speech-bubble">${commentData.text}</div>`;
$(".commentList").append(temp_html);
});
//addDoc ์๋ต
});
์์ ๋ฐฉ์์ ๋ฐ์ดํฐ๊ฐ ์ค์๊ฐ์ผ๋ก ๋ฐ์๋์ง ์์๋ค.
์ฐ์ import๋ฅผ ํด์ค์ผ ์ธ ์ ์๊ฒ ์ฃ ?
import { onSnapshot } from "https://www.gstatic.com/firebasejs/9.22.0/firebase-firestore.js";
+์
๋ ฅ ํ $("#commenting").val("")๋ก ์
๋ ฅ์ฐฝ ์ด๊ธฐํ
->๋๊ธ ์์ฑ ํ ์
๋ ฅ์ฐฝ์ด ๋น์์ง.
//1
onSnapshot(collection(db, "commenting"), (snapshot) => {
$(".commentList").empty(); // ๊ธฐ์กด ๋ชฉ๋ก ์ด๊ธฐํ
//2, 3
snapshot.docs
.sort((a, b) => a.data().timestamp - b.data().timestamp) // ์๊ฐ์ ์ ๋ ฌ
.forEach((doc) => {
let commentData = doc.data();
let temp_html = `<div class="speech-bubble">${commentData.text}</div>`;
$(".commentList").append(temp_html);
});
})
โ
onSnapshot()์ ์ฌ์ฉํ๋ฉด getDocs() ์์ด๋ Firestore ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ฌ ์ ์๋ค!
โ
onSnapshot()์ Firestore ๋ฐ์ดํฐ๋ฅผ ์ค์๊ฐ์ผ๋ก ๊ฐ์ํ๋ฉด์ ์๋์ผ๋ก UI๋ฅผ ์
๋ฐ์ดํธํด ์ฃผ๊ธฐ ๋๋ฌธ์, ํ์ด์ง ๋ก๋ฉ ํ ๋ณ๋๋ก getDocs()๋ฅผ ์คํํ ํ์๊ฐ ์๋ค!
์์ฑ๋ ํ๋ฉด์ ํ๋ฒ ๋ณด์

๋๊ธ์ด ์ ๋ฌ๋ฆฌ๋ ๊ฒ์ ํ์ธํ ์ ์์๋ค!
๋๊ธ ๊ธฐ๋ฅ์ ์ถ๊ฐํ๊ธฐ ์ํด addํ๊ณ onSnapshot์ผ๋ก ์ค์๊ฐ ๋ฐ์๊น์ง ๊ตฌํํ๋๋ฐ, ๋๊ธ์ด ์์๋๋ก ๋ฐฐ์น๋์ง ์๊ณ ๋๋คํ ์์๋ก ๋ฐฐ์น๋๋ ๊ฒ์ ํ์ธํ ์ ์์๋ค.
โ ๋๊ธ์ ์ค๋๋๊ฑด ์๋ก, ์ต์ ๊ฒ์ด ์๋์ชฝ์ผ๋ก ๋ฐฐ์ด๋๊ฒ ๋ง๋ค๊ณ ์ถ์๊ธฐ ๋๋ฌธ์ด๋ค.(์ค๋ฆ์ฐจ์ ๋ฐฐ์ด)
collection(db, "commenting") โ "commenting" ์ปฌ๋ ์
์์ ๋ชจ๋ ๋ฌธ์๋ฅผ ๊ฐ์ ธ์.
orderBy("timestamp", "asc") โ ๊ฐ์ ธ์จ ๋ฌธ์๋ค์ timestamp ๊ธฐ์ค์ผ๋ก ์ค๋ฆ์ฐจ์(asc) ์ ๋ ฌ!
๐ก orderBy("timestamp", "asc")โ ์์ฑ๋ ์๊ฐ์(์ค๋๋ ์)์ผ๋ก ์ ๋ ฌ
"asc" (์ค๋ฆ์ฐจ์) โ ์ค๋๋ ๋๊ธ์ด ์์ชฝ
"desc" (๋ด๋ฆผ์ฐจ์) โ ์ต์ ๋๊ธ์ด ์์ชฝ
query()๋ฅผ ํ์ฉํด์ผ firestore์์ ์กฐ๊ฑด์ ์ ์ฉํ ์ ์๊ธฐ ๋๋ฌธ์ ๋์ ๋ฌถ์ด์ฃผ๋ ์ฟผ๋ฆฌ๋ฅผ ์ฌ์ฉํ๋ค
๐ฅ ์ฆ, query()๋ Firestore์์ ํน์ ์กฐ๊ฑด(์ ๋ ฌ, ํํฐ ๋ฑ)์ ์ ์ฉํ ๋ ๊ผญ ํ์ํ๋ค!!
๋ฌถ์ ์ฟผ๋ฆฌ๋ฅผ const๋ก ์ ์ํด์ฃผ์
const q = query(collection(db, "commenting"), orderBy("timestamp", "asc"));
onSnapshot(q, (snapshot) => {
๋๊ธ์ด ์ค์๊ฐ์ผ๋ก ๋ฐ์๋์ด์ผํ๋ฏ๋ก snapshot์ ์ ์งํ๋, ์๊น ์ค๋ฆ์ฐจ์์ผ๋ก ์ ์ํ ์ฟผ๋ฆฌ q์ ์๋ ๊ฐ์ ์จ์ผํ๋๊น ์์ ์ฝ๋์ฒ๋ผ ์ ์ํ์
โ query()๋ฅผ ์ฌ์ฉํด์ผ orderBy() ๊ฐ์ ์กฐ๊ฑด์ Firestore์์ ์ ์ฉํ ์ ์์.
โ orderBy("timestamp", "asc")๋ก ์ ๋ ฌํ๋ฉด ์๊ฐ์ ์ ๋ ฌ์ด ๋จ.