I'm trying to pass a Binding to my VM which is supposed to be a filter so the VM fetches objects according to the filtering passed by params.
Unfortunately, I'm not able to initialize the VM, as I'm getting the error 'self' used before all stored properties are initialized in the line where I'm initializing my VM self.jobsViewModel = JobsViewModel(jobFilter: $jobFilter)
struct JobsTab: View {
@ObservedObject var jobsViewModel: JobsViewModel
@ObservedObject var categoriesViewModel: CategoriesViewModel
@StateObject var searchText: SearchText = SearchText()
@State private var isEditing: Bool
@State private var showFilter: Bool
@State private var jobFilter: JobFilter
init() {
self.categoriesViewModel = CategoriesViewModel()
self.jobFilter = JobFilter(category: nil)
self.showFilter = false
self.isEditing = false
self.jobsViewModel = JobsViewModel(jobFilter: $jobFilter)
}
I think I'm initializing all the vars, and self.searchText isn't in the init block because the compiler complains that it is a get-only property.
Is there any other way to do this?
Thanks!
EDIT: Here's my VM:
class JobsViewModel: ObservableObject {
@Published var isLoading: Bool = false
@Published var jobs: [Jobs] = []
@Binding var jobFilter: JobFilter
init(jobFilter: Binding<JobFilter>) {
_jobFilter = jobFilter
}
...
}
struct JobFilter {
var category: Category?
}
My idea was to have the job filter as a state in the JobsTab, and every time that state changes, the VM would try to fetch the jobs that match the JobFilter
onAppear? where should I do that, in theJobsTabor in theJobsViewModel?JobsTabViewModelwhich you have initialised with aJobsModeland aCategoriesModelor something; this view shouldn't know anything about other views viewmodels