Array is null after trying to fetch data in swift app

Viewed 33

I am trying to save an array which I have stored in firestore in a local array

this is the method where the error occurs:

 func getEvents() async {
        let db = Firestore.firestore()
        var allEvents = [String]()
        var docIDuser = ""
        docIDuser = UserDefaults.standard.object(forKey: "userDocID") as! String
        
   
     try? await db.collection("user").document(docIDuser).getDocument() { (document, error) in
            if let document = document, document.exists {
                allEvents = (document.data()!["events"] as? [String])!
            } else {
                print("Document does not exist")
            }
        }
    
        for element in allEvents {
            try? await db.collection("event").document(element as! String).getDocument() { (document, error) in
                if let document = document, document.exists {
                    let ev = document.data()!
                    self.eventlist.append(Event(id: document.documentID, name: document["eventname"] as? String ?? ""))
                } else {
                    print("Document does not exist")
                }
            }
        }
    }

I tried to debug the code and within this part:

try? await db.collection("user").document(docIDuser).getDocument() { (document, error) in
            if let document = document, document.exists {
                allEvents = (document.data()!["events"] as? [String])!
            } else {
                print("Document does not exist")
            }
        }

allEvents is filled with the values that I need but as soon as I leave the block, allEvents doesn't have any values left. It is probably an async problem but I don't get why it isn't working since I am trying to avoid this issue by implementing async/await

this is where I call the method:

 Button(action: {
                    Task {
                        try? await viewModel.getEvents()
                    }
                }, label: {
                    Text("events test")
                })

any help would be appreciated

0 Answers
Related