In Firestore documentation(https://firebase.google.com/docs/firestore/query-data/listen),
You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document. Then, each time the contents change, another call updates the document snapshot.
However, I just want my listener to fire when the data changes. I don't want it to fire when the app loads, to get the initial state of the data.
I searched the Internet and found a hint.(Can Cloud Firestore onSnapshot() only trigger on changes, and not get the initial state?)
If you want to receive only certain data, you might want to figure out how to query for it, for example, by adding a timestamp field and having the client only query for documents that have changed since some prior time.
Does this mean .where('createdDate', '>=', new Date())
?
I put this in my code. For example,
firebase
.firestore()
.collection('script')
.where('createdDate', '>=', new Date())
.orderBy('createdDate', 'desc')
.limit(1)
.onSnapshot(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
console.log(doc.data().text);
const textarea = document.createElement('textarea');
textarea.value = doc.data().text;
textarea.rows = '5';
textarea.cols = '40';
textarea.id = 'textarea';
const parent = document.getElementById('textbox');
parent.appendChild(textarea);
const upload = document.createElement('BUTTON');
upload.innerHTML = 'スピーチを提出'
upload.addEventListener("click", function(event){
const resultText = document.getElementById('textarea');
firebase.firestore().collection('final').add({
text: resultText.value
}).catch(function(error){
console.error('Error writing', error);
});
});
parent.appendChild(upload);
});
});
But it didn't work. Could you give me any advice?
createdDate
field is greater than now? Are you sure you didn't mean to usetimestamp
instead ofcreatedDate
? – Doug StevensonAre you sure you didn't mean to use timestamp instead of createdDate?
=> I didn't notice that mistake and now I edited it. Excuse me. I have no ideas for other comments. – Kazuaki SuzukicreatedDate
greater/newer than the one that you are comparing too? You need to be sure that you will have a document that will fit your comparsion. In addition, have you tried the solution proposed here? – gso_gabriel