Foremost, I wanted to say thank you to Chris and his crew! You know somehow how to explain any topic so it becomes so clear and logical.
To my problem and may be suggestion for a new video. It’s about in depth property programming, when you work with real life nosql database and MVVM pattern. When you cannot see the result of code actions in order to interact with them further.
I am a bit stuck with creating right model (in terms of MVVM) with use of NoSQL Firebase Firestore.
In short. I have two lists of data (parent and child list). Let say List of “Skills” and a list of “Sub Skills” which goes out of itch Skill. User pics Skill from presented Skill List then Sub Skills from child list of chosen Skill.
I can fetch those lists from Firestore using this code
to fetch Skill
import SwiftUI
import Firebase
struct Skill: Identifiable {
var id: String = UUID().uuidString
var skillName: String
}
class getSkillList: ObservableObject {
@Published var skills = [Skill]()
private var db = Firestore.firestore()
func fetchData() {
db.collection("skills").addSnapshotListener { (querySnapshot, error) in
guard let documents = querySnapshot?.documents else {
print("No documents")
return
}
self.skills = documents.map { (queryDocumentSnaoshot) -> Skill in
let data = queryDocumentSnaoshot.data()
let skillName = data["skillName"] as? String ?? ""
return Skill(skillName: skillName)
}
}
}
}
struct SkillListView: View {
@ObservedObject private var viewModel = getSkillList()
var body: some View {
List(viewModel.skills) { skill in
Text(skill.skillName)
}.navigationBarTitle("Skills")
.onAppear(){
self.viewModel.fetchData()
}
}
}
And similar to fetch Sub Skill
import SwiftUI
import Firebase
struct SubSkill: Identifiable {
var id: String = UUID().uuidString
var subSkillName: String
}
class getSubSkillList: ObservableObject {
@Published var subSkills = [SubSkill]()
private var db = Firestore.firestore()
func fetchDataS() {
db.collection("skills").document("18GES4eV2LOhzZc38A2M").collection("subSkills").addSnapshotListener { (querySnapshot, error) in
guard let documents = querySnapshot?.documents else {
print("No documents")
return
}
self.subSkills = documents.map { (queryDocumentSnaoshot) -> SubSkill in
let data = queryDocumentSnaoshot.data()
let subSkillName = data["subSkillName"] as? String ?? ""
return SubSkill(subSkillName: subSkillName)
}
}
}
}
struct SubSkillListView: View {
@ObservedObject private var viewModelS = getSubSkillList()
var body: some View {
List(viewModelS.subSkills) { subSkill in
Text(subSkill.subSkillName)
}.navigationBarTitle("Sub Skills")
.onAppear(){
self.viewModelS.fetchDataS()
}
}
}
However since the data is fetched out of database I cannot see the list (in a code) it self to add navigation link to it from Skill select out of Skill list to Sub skill list and etc.
I know that it should be done somehow out of programmed properties but I cannot figure out how (staying within MVVM pattern).
Will greatly appreciate for any help!