I am trying to create a class that it runs a Firebase requests and saves the result in variables. Then from different views I access the variables. Each variable will be for one category.
I have made a class in the same view as I am showing the data in the app, and it is working. But when I move it to a separate swift file, it gives the following error:
struct ContentView: View {
var body: some View {
Home()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct Home : View {
@ObservedObject var categories = getCategoriesData()
var body: some View {
// Error: Unable to infer complex closure return type; add explicit type to disambiguate
VStack {
List(categories.datas) { i in
Text(i.name)
}
}
}
}
Swift file:
class getCategoriesData : ObservableObject {
@Published var datas = [category]()
init () {
let db = Firestore.firestore()
db.collection("ingredients").addSnapshotListener{ (snap, err) in
if err != nil {
print((err?.localizedDescription)!)
return
}
for i in snap!.documentChanges {
let id = i.document.documentID
let name = i.document.get("name") as! String
self.datas.append(category(id: id, name: name))
}
}
}
}
struct category : Identifiable {
var id : String
var name : String
}
Just to be clear, right now I am getting data from ingredients
category in Firebase, I want to rerun the class and store each category result in an array/map datas
in this case so then I can access them in different views. OR have it in a different class so for each view I run the DB request and get data for one of the categories.
Any idea how to make this working?
Thanks