[英]How do I count up in Firebase Firestore in front-end
我正在創建一個允許用戶跟蹤新習慣的應用程序,使用 Firestore 來保存用戶的數據。 存儲在數據庫中的數據如下:
我的目標是基本上點擊 object(在本例中為#container
中的火焰),並將計數加到數據庫中。
這就是我現在得到的:
// Real-time listener
db.collection('habits').onSnapshot((snapshot) => {
snapshot.docChanges().forEach(change => {
if(change.type === 'added'){
renderHabit(change.doc.data(), change.doc.id);
}
});
})
// Add new habit
const form = document.querySelector('form');
form.addEventListener('submit', evt => {
evt.preventDefault();
const habit = {
title: form.habitTitle.value,
count: 0,
goal: form.habitGoal.value,
streak: 0
};
db.collection('habits').add(habit)
.catch(err => console.log(err));
form.habitTitle.value = '';
form.habitGoal.value = '';
})
// Update counter
const habitContainer = document.querySelector('.newHabit');
habitContainer.addEventListener('click', evt => {
//console.log(evt);
if(evt.target.tagName === 'I'){
const id = evt.target.getAttribute('data-id');
db.collection('habits').doc(id).update({
count: 1
});
}
});
const habits = document.querySelector('.newHabit');
// Render habit data
const renderHabit = (data, id) => {
const html = `
<div id="wrapper" data-id="${id}">
<div id="container">
<span id="title">${data.title}</span>
<div class="streakContainer">
<span id="streak">${data.streak}</span>
<i data-id="${id}">🔥</i>
</div>
<div class="countContainer">
<span id="count">${data.count}</span>
<span>/</span>
<span id="goal">${data.goal}</span>
</div>
<div id="progressbar">
<div id="timer"></div>
<div id="progressbaroverlay"></div>
</div>
</div>
</div>
`;
habits.innerHTML += html;
};
我試圖聲明var countNumber = 0;
最終在// Update counter
內部的 clickevent 上使用countNumber = countNumber++
,這不起作用,因為 countNumber 在刷新時再次設置為 0 (我相信)。
希望我足夠清楚:)
謝謝!
在數據庫中遞增數字的最簡單方法是使用increment
運算符:
habitContainer.addEventListener('click', evt => {
if(evt.target.tagName === 'I'){
const id = evt.target.getAttribute('data-id');
db.collection('habits').doc(id).update({
count: firebase.firestore.FieldValue.increment(1)
});
}
});
每次你調用它,你的onSnapshot
監聽器都會被更新的文檔再次調用。 您需要在其中處理if(change.type === 'modified'){
以在 UI 中顯示更新的值/文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.