Luis Quiroga
Luis Quiroga

Reputation: 768

Firestore is running a query twice when I use query operators and the second time I get null as response

I want to get from firestore all the documents in a collection ("invitations") where the date is equal or greater than today at 00:00:00 and some other parameters.

My function is:

var today_init = new Date()
today_init.setHours(0, 0, 0, 0)

let query = await db.collection("invitations")
  .where("date", ">=", today_init)
  .where("sender.user_uid", "==", Fire.user.uid)
  .where('data.is_here', '==', false)

query.onSnapshot(async (querySnapshot) => {
  try {
    console.log(querySnapshot)

    //more code here....
  }catch(error){ 
    console.log(error)
  }

What is happening is that it runs twice automatically, the first execution it returns the firestore documents that I want, and the next execution it returns null.:

TWICE EXECUTION

So, obviously the first response is the one that I want, but I don't know why is running twice or what is really happening but that null value ruins my logic.

When I comment the line:

.where("date", ">=", today_init)

The query runs perfectly. The think is that I don't want the old invitations.

PS. I'm using react-native

Upvotes: 0

Views: 764

Answers (1)

Luis Quiroga
Luis Quiroga

Reputation: 768

After a while I came up with this:

await db.collection("invitations")
  .where("date", ">", today_init)
  .where("sender.user_uid", "==", Fire.user.uid)
  .where("data.is_here", "==", false)
  .orderBy("date", "desc")
  .onSnapshot((querySnapshot) => {
    console.log(querySnapshot)

  }, function (error) {
    console.log(error)
  })

The error callback function helped me to create the index.

More info : https://firebase.google.com/docs/firestore/query-data/listen#handle_listen_errors

Upvotes: 2

Related Questions