Learn Courses My Dashboard

Can't get data from firebase with codable

I am having problems getting data from the firestore using the codable protocol

Here is my function

import SwiftUI
import Firebase
import FirebaseFirestore
import FirebaseFirestoreSwift


class UsersModel: ObservableObject {
    
    @Published var userData = [UserData]()
    
    let userID = Auth.auth().currentUser!.uid
    
    private var db = Firestore.firestore()
    
    func fetchData() {
        
        db.collection("users").document(userID).addSnapshotListener { (querySnapshot, error) in
            guard let document = querySnapshot?.data() else {
                print("No documents")
                return
            }
            
            self.userData = document.compactMap{(QueryDocumentSnapshot) -> UserData? in
                return try? QueryDocumentSnapshot.data(as: UserData.self)
            }
        }
    }
    
}

and here is my users struct

import SwiftUI
import FirebaseFirestoreSwift

struct UserData: Identifiable, Codable {
    @DocumentID var id: String?
    var username: String
    var ImageURl: URL
}


on the line return try? QueryDocumentSnapshot.data(as: UserData.self)

I get this error Value of tuple type 'Dictionary<String, Any>.Element' (aka '(key: String, value: Any)') has no member 'data'

How can I fix this

Welcome to the community! What does your firebase structure look like? The error is saying you’re referring to .data When that doesn’t exist