Home > Back-end >  What is the best way to store a ToDo on Firestore?
What is the best way to store a ToDo on Firestore?

Time:08-04

I recently followed the build a to do list app with SwiftUI and Firestore run by Peter Friese on YouTube. The ToDos had a boolean completed attribute to indicate whether or not they are complete and they are fetched with a snapshot listener.

Below is an example of a ToDo item that is stored and retrieved from my Firestore collection.

struct ToDo: Identifiable, Codable {
    @DocumentID var id: String?
    var title: String = ""
    var completionDate: Date?
    var userId: String?
}

I wanted to achieve the following functionality:

  • Incomplete ToDos would be fetched
  • Complete ToDos in the last 24 hours would be fetched

Due to the time functionality I swapped the Boolean attribute for a completion date that gets updated every time the user checks or unchecks whether or not they have complete a ToDo.

Regarding my last question, I discovered that I cannot query for ToDos that have a nil value nor can I make this an OR statement to retrieve the completed ToDos in the last 24 hours in one query.

Is it possible to have the above functionality with one query and one snapshot listener?

CodePudding user response:

If you default the completionDate to a timestamp very far in the future, you can get all documents that were completed in the past 24h and that are not yet completed with a single query on that field.

todoRef.whereField("completionDate", isGreaterThan: timestampOfYesterday)

In your application code, you will then have to identify the documents with the default completionDate and mark them as incomplete in your UI.

  • Related