0
votes

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?

1
"But it didn't work" - that's not enough information to go on. What exactly are you doing and observing? What do you expect the query to do? What did you do with your data to make sure that you only get the documents where the createdDate field is greater than now? Are you sure you didn't mean to use timestamp instead of createdDate?Doug Stevenson
@DougStevenson Thank you for your reply. Are 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 Suzuki
Hi @KazuakiSuzuki could you please clarify what didn't work? It didn't return any documents? Considering that, have you confirmed that you have a document with a createdDate 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
@gso_gabriel Thank you very much for your advice. To tell the truth, I didn't know how to write error function, so I couldn't know what didn't work. Yes, it didn't return any document. Thanks to your hint I am able to solve my problem.Kazuaki Suzuki

1 Answers

1
votes

Thanks to @gso_gabriel 's comment, I can solve my problem.

var initState = true;
firebase
  .firestore()
  .collection('script')
  .orderBy('createdDate', 'desc')
  .limit(1)
  .onSnapshot(function (querySnapshot) {
    console.log(`Received doc snapshot`);
    if (initState) {
        initState = false;
    } else {
        if (!querySnapshot.docChanges().empty) {     
            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);
            });
        }
    }
}, err => {
    console.log(`Encountered error: ${err}`);
});