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

Firebase work with sub collections getting empty

Forums > Swift

Im trying to work with subcollection in the main object but when I try to loop in subcollections I get empty

Simplified I have this


struct Main: Identifiable, Decodable {
    @DocumentID var id: String?

    var title: String 
}

And the subcollection

struct SubCollection: Identifiable, Decodable {
    @DocumentID var id: String?

    var subCollectiontitle: String 
}

When I initialize the viewModel I use

@Published var mains = [Main]()

init() {
      fetchMain()
}

Now how is the proper way to get the Subs of a main ?

When I use this on a method

func fetchSubs() -> [SubCollection] {
  var subs = [SubCollection] ()
        for main: Main in self.mains {
            if let id = main.id {
                Firestore.firestore().collection("mains").document(id).collection("sub-collection").getDocuments { snapshot, _ in
                    guard let documents = snapshot?.documents else { return }
                    subs = documents.compactMap({ try! $0.data(as: SubCollection.self)})
                }
            }
        }

        return subs
    }

Always is empty, but when I do it in the init gets the data

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.