如何在不刷新页面的情况下从Firestore云界面删除数据后更新视口



我正在使用jQuery更新表单,当我从Firestore界面删除数据时,它不会在不刷新页面的情况下自动反映在我的视口中。我正在寻找一种从Cloud Firestore实时更新数据的方法。

//Update button function
$('.save-button').on('click', function (event) {
$('train-table').empty();
event.preventDefault();
//takes in form inputs
var timetable = {
name: $('.name-input').val(),
destination: $('.destination-input').val(),
frequency: $('.frequency-input').val(),
}
// Add new documents with a generated id.
var addDoc = firestore
.collection('train-schedule')
.add({ timetable })
.then(function (ref) {
try {
console.log("Status- Saved with ID: ", ref.id);
} catch (error) {
console.log("Got an error", error);
}
});
});
//get real time updates
getRealTimeUpdates = function () {
trainCollection.onSnapshot(function (snapshot) {
snapshot.forEach(doc => {
var myData = doc.data().timetable;
console.log("Train Id: ", doc.id);
$(".train-table").append(
"<tr><td id='name-col'>" + myData.name +
"<td id='destination-col'>" + myData.destination +
"<td id='frequency-col'>" + myData.frequency + "</td></tr>");
});
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
getRealTimeUpdates();

});

我希望在从Firestore界面删除数据时视口会更新。

据我所见,您只是将数据附加到HTML中。因此,当有任何更改时(即使文档被删除),您只需将所有剩余文档的HTML添加到表的末尾。

简单的解决方案是在重新呈现其内容之前清除表:

trainCollection.onSnapshot(function (snapshot) {
$(".train-table").clear(); // clear the existing documents before rerendering
snapshot.forEach(doc => {
var myData = doc.data().timetable;
console.log("Train Id: ", doc.id);
$(".train-table").append(
"<tr><td id='name-col'>" + myData.name +
"<td id='destination-col'>" + myData.destination +
"<td id='frequency-col'>" + myData.frequency + "</td></tr>");
});
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});

一种更有效的方法是通过查看QuerySnapshot.docChanges来实际检查更改了什么,并在此基础上对HTML进行更细粒度的更新。另请参阅有关侦听快照之间的更改的文档。

最新更新