Type 'Void' cannot conform to 'View' | Swift

Viewed 1582

I'm trying to create a List with data from my firebase reali-time database but i'm getting this error on the List line:

The error:

Type 'Void' cannot conform to 'View' 

My code: struct ActiveGoalsView: View {

    @State var goals = ["finish this project"]
    @State var ref = Database.database().reference()
    
    var body: some View {
        NavigationView {
            List {
                
                ref.child("users").child(Auth.auth().currentUser?.uid ?? "noid").child("goals").observeSingleEvent(of: .value) { snapshot in
                    
                    for snap in snapshot.children {
                        Text(snap.child("title").value)
                    }
                }
                
            }.navigationBarHidden(true)
        }
    }
}

struct ActiveGoalsView_Previews: PreviewProvider {
    static var previews: some View {
        ActiveGoalsView()
    }
}
1 Answers

You can't use imperative code like observeSingleEvent in the middle of your view hierarchy that doesn't return a View. As a commenter suggested, you'd be better off moving your asynchronous code outside of the body (I'd recommend to an ObservableObject). Here's one solution (see inline comments):

class ActiveGoalsViewModel : ObservableObject {
    @Published var children : [String] = []
    
    private var ref = Database.database().reference()

    func getChildren() {
        ref.child("users").child(Auth.auth().currentUser?.uid ?? "noid").child("goals").observeSingleEvent(of: .value) { snapshot in
            
            self.children = snapshot.children.map { snap in
                snap.child("title").value //you may need to use ?? "" if this returns an optional
            }
        }
    }
}

struct ActiveGoalsView: View {
    @State var goals = ["finish this project"]
    @StateObject private var viewModel = ActiveGoalsViewModel()

    var body: some View {
        NavigationView {
            List {
                ForEach(viewModel.children, id: \.self) { child in //id: \.self isn't a great solution here -- you'd be better off returning an `Identifiable` object, but I have no knowledge of your data structure
                    Text(child)
                }
            }.navigationBarHidden(true)
        }.onAppear {
            viewModel.getChildren()
        }
    }
}
Related