Home > Back-end >  Why is my function returning an empty array?
Why is my function returning an empty array?

Time:03-24

I am trying to call the results of this function in my SwiftUI view:

class GetMessages: ObservableObject {
    let BASE_URL = "apicallurl.com"
    @Published var messages = [Timestamp]()
    func fetchMessages() {
        guard let url = URL(string: BASE_URL) else { return }
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard error == nil else {print(error!.localizedDescription); return }
            let theData = try! JSONDecoder().decode([String: Timestamp].self, from: data!)
            DispatchQueue.main.async {
                self.messages = Array(theData.values)
            }
        }
        .resume()
    }
}

I am testing the output with a print statement in the onAppear:

struct HomeTab: View {
  @StateObject var getMsgs = GetMessages()
  var body: some View {
    NavigationView {
        VStack(spacing: 0) {
            greeting.edgesIgnoringSafeArea(.top)
            messages
            Spacer()
        }
       .onAppear {
           print(getMsgs.fetchMessages())
           print(getMsgs.messages)
       }
    }.navigationBarHidden(true)
}

both print statements print () or [] But when i print print(self.messages) in my GetMessages class the data prints fine.

Why is it empty in my Hometab view?

CodePudding user response:

When you use getMsgs.fetchMessages() it may take some times to fetch the results. Once the results are available the messages of getMsgs in HomeTab will be updated, and this will trigger a view refresh, because it is a @StateObject and is "monitored" by the view.

However you should not try to print(getMsgs.messages) before the results are available.

So try the following sample code:

struct HomeTab: View {
    @StateObject var getMsgs = GetMessages()
    
    var body: some View {
        NavigationView {
            List {
                ForEach(getMsgs.messages, id: \.self) { msg in
                    Text("\(msg)") 
                }
            }
            .onAppear {
                getMsgs.fetchMessages()
                // no printing of getMsgs.messages here
            }
        }.navigationBarHidden(true)
    }
}
  • Related