UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Passing a Firestore document ID from another collection into another Query?

Forums > SwiftUI

Hi everyone,

I’ve been using Firestore to work with a data model around storing plants and their respective reminders/diary entries. The setup is like this:

Collection: UserPlants Collection: Users Collection: PlantLog - Holds reference to UserPlants (through plantRef) and Users (through UserRef)

I’ve been able to successfully access these collections and documents via userRef and the plantRef, but the trouble I’m facing is figuring out how to pass-through the plantRef (a string ID) programatically to the ViewModel for fetching diary entries in the PlantLog.

Right now, each plant is created through the following:

struct HomePlantsView: View {
    @StateObject var plantData = UserPlantViewModel()

    HStack {
                ForEach(plantData.plants) {plant in
                    HomePlantCardView(plant: plant)
                }
                }
            }

Each HomePlantCardView references the UserPlants class through var plant: UserPlants. The UserPlants model looks something like this:

struct UserPlants : Identifiable, Codable {
    @DocumentID var id: String? = UUID().uuidString
    var dateCreated: Date
    var plantName: String
    var userRef: String

    enum CodingKeys: String, CodingKey {
        case id
        case dateCreated
        case plantName
        case userRef
      }
}

Each plant then has diaries. These diaries are represented by the PlantDiary model:


struct PlantDiary : Identifiable, Codable {
    @DocumentID var id: String? = UUID().uuidString
    var dateCreated: Date
    var note: String?
    var userRef : String
    var plantRef: String

    enum CodingKeys: String, CodingKey {
        case id
        case dateCreated
        case note
        case userRef
        case plantRef
      }
}

Both the HomePlantCardView and diaries within have their own ViewModels where I have functions fetching data from Firestore.

At first, I thought of using the onAppear function to call the Plant ID within the UserPlants class and pass it into the DiaryViewModel, but that wasn't working well. Currently, I'm able to add a new diary entry with both the plantRef and userRef, but I'm just struggling to figure out how to actually present each plant uniquely with its Diary entries by fetching the data like this in PlantDiaryViewModel:

func fetchData() {
        let userId = Auth.auth().currentUser!.uid

        ref.collection("PlantLog")
            .order(by: "dateCreated", descending: true)
            .whereField("userRef", isEqualTo: userId)
            .whereField("plantId", isEqualTo: "THIS SHOULD BE THE PLANTREF THAT I WANT TO PROGRAMATICALLY PASS")

            .addSnapshotListener { (snap, err) in

            print("In fetch Diary Data and mapping documents...")

            guard let docs = snap else{
                self.noPosts = true
                return
            }

            self.diaries = docs.documents.compactMap { (queryDocumentSnapshot) -> PlantDiary? in

                return try? queryDocumentSnapshot.data(as: PlantDiary.self)
            }
        }

    }

Does anyone have any ideas/thoughts? I feel like it has to do with the var plants: UserPlants piece and the UserPlants class, but just can't figure it out. Thanks!

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.