title: Firestore: What is the efficient way to list messages in chat?
body: <p>I am trying to create a chat like app using Firestore and trying to list all messages in chat and updates it every time when a message is added.</p>
  
  <p>I tried this way first to implement it.</p>
  
  <pre><code>mounted() {
  
      docRef.collection('messages').orderBy('timestamp', 'desc').limit(1).onSnapshot((querySnapShot) =&gt; {
          querySnapShot.forEach((doc) =&gt; {
              if (!doc.metadata.hasPendingWrites) {
                  this.messages.push(doc.data())
              }
          })
      })
  
  }
  </code></pre>
  
  <p>This way seems efficient because this way only gets the latest message in collection. However, I found out this way has a problem. When a user refreshs a page, the user can't get the past messages.</p>
  
  <p>So I changed it like this.</p>
  
  <pre><code>mounted() {
      docRef.collection('messages').orderBy('timestamp', 'asc').onSnapshot((querySnapShot) =&gt; {
          querySnapShot.docChanges().forEach((change) =&gt; {
              if (change.type === 'added') {
                   this.messages.push(change.doc.data())
                }
          })
      })
  }
  </code></pre>
  
  <p>This way works as I expected. But this way needs a lot of requests because every time the collection is changed I need to read all the documents in the collection.</p>
  
  <p>What is the efficient way to list messages in chat?</p>
  
  <p>I thought it works if I get all the current messages first and set the listener for new messages but the listener is triggered immediately after I enter the page even though there is no change in the collection and read the latest message twice.</p>