CodableFirebase icon indicating copy to clipboard operation
CodableFirebase copied to clipboard

I need to get the documentID populated in a "docId" variable in my struct

Open Benjamin-Ashamole opened this issue 4 years ago • 2 comments

I have a struct that looks like the code below. I've also written a generic class, and a function "loadItems()" to read items from firestore (See code below) When the snapshotdata is decoded to the type that T represents, the documentID isn't mapped to any of the fields in the struct. I've search around a fair bit and can't find any solution that works for me since I'm using generics i can just assign it in the loop where i decode the data.

struct CartItem: Codable & Equatable {
    
    enum CodingKeys: String, CodingKey {
        
        case userId = "userId"
        case docId = "docId"
        case productName = "productName"
        case quantity = "quantity"
        case imageName = "imageName"
        case name = "name"
        case email = "email"
        case measure = "measure"
        case phone = "phone"
        case description = "description"
        case address = "address"
        case price = "price"
    }

    let userId: String?
    let docId: String?
    let productName: String?
    let quantity: String?
    let description: String?
    let imageName: String?
    let name: String?
    let email: String?
    let price: String?
    let measure: String?
    let phone: String?
    let address: [String: String]?
}
func loadItems(completion: @escaping ([T])-> Void) -> [T] {
        handle = Auth.auth().addStateDidChangeListener { (auth, user) in
            if ((user) != nil) {
                self.ref = self.db.collection(self.collectionName).whereField("userId", isEqualTo: user!.uid)
                self.ref?.getDocuments(completion: { (querySnapshot, err) in
                    if let err = err {
                        print("Error getting documents: \(err.localizedDescription)")
                            }
                    else {
                        if let snapshotDocs = querySnapshot?.documents {
                            for doc in snapshotDocs {
                                var data = try! FirestoreDecoder().decode(T.self, from: doc.data())
                                self.items.append(data)
                            }
                            completion(self.items)
                        }
                    }
                })
            }
            else {
                
                print("Not Logged In")
                self.items = []
            }
        }
        return items
    }

Benjamin-Ashamole avatar May 03 '21 17:05 Benjamin-Ashamole

Did you solve this?

Crysis21 avatar Jul 15 '21 06:07 Crysis21

I did. But with more of a work around than fixing the actual Issue.

Benjamin-Ashamole avatar Jul 21 '21 15:07 Benjamin-Ashamole