I am trying to make use of init
to call the fetchProducts
function in my ViewModel
class. When I add init
though, I am getting the following 2 errors:
Variable 'self.countries' used before being initialized
and
Return from initializer without initializing all stored properties
The variable countries
is binding though so there shouldn't need to be an initialized value in this view. Am I using init
incorrectly?
struct ContentView: View {
@Namespace var namespace;
@Binding var countries: [Country];
@Binding var favLists: [Int];
@State var searchText: String = "";
@AppStorage("numTimeUsed") var numTimeUsed = 0;
@Environment(\.requestReview) var requestReview
@StateObject var viewModel = ViewModel();
init() {
viewModel.fetchProducts()
}
var body: some View {
}
}
CodePudding user response:
Look at the initialiser that autocomplete gives you when you use ContentView
…
ContentView(countries: Binding<[Country]>, favLists: Binding<[Int]>)
If you're creating your own initialiser, it will need to take those same parameters, e.g.
init(countries: Binding<[Country]>, favLists: Binding<[Int]>) {
_countries = countries
_favLists = favLists
viewModel.fetchProducts()
}
Alternatively, use the default initialiser, and instead…
onAppear {
viewModel.fetchProducts()
}