I am trying to get the collection from firebase firestore. Below is my ViewModel I am unable to store the data in the @Published var categories object. I am unable to find the exact issue, I am a bit new to swift but the exact same thing was working a while back is there something I am doing wrong?
FormViewModel.swift
import Firebase
import FirebaseFirestore
class FormViewModel: ObservableObject {
@Published var categories = [Category]()
private var db = Firestore.firestore()
func fetchCategories() {
db.collection("companies_by_category").addSnapshotListener { (QuerySnapshot, error) in
guard let documents = QuerySnapshot?.documents else {
print("No documents")
return
}
self.categories = documents.compactMap { (QueryDocumentSnapshot) -> Category? in
return try? QueryDocumentSnapshot.data(as: Category.self)
}
print(self.categories) // -> Able to get data
}
}
}
My CategoriesView
struct CategoriesView: View {
@ObservedObject var viewmodel = FormViewModel()
var body: some View {
ScrollView {
List(self.viewmodel.categories) { category in
ZStack {
RoundedRectangle(cornerRadius: 15, style: .continuous)
//.foregroundColor(category.selected == true ? Color.yellow.opacity(0.5) : Color.white)
.foregroundColor(.white)
.shadow(color: Color.black.opacity(0.1), radius: 10, x: 0, y: 0)
VStack(spacing: 20) {
HStack {
Image("\(category.category)")
.foregroundColor(Color.gray)
.font(.system(size: 20.0))
Text(category.category)
.font(.system(size: 20.0, weight: .medium))
.foregroundColor(Color.black)
Spacer()
}
}
.padding()
}
}
}
.onAppear() {
self.viewmodel.fetchCategories()
}
}
}