I have recently started using SwiftUI and have build up a simple app that fetches data from a web service. I have following code in my View
struct ProductsView: View {
@EnvironmentObject var viewModel: ProductViewModel
var body: some View {
NavigationView {
List(content: {
ForEach(viewModel.products, id: .self) { product in
ProductRow(product: product)
}
})
.padding()
}
.task {
try? await viewModel.fetchProducts()
}
.alert(isPresented: $viewModel.showError) {
Alert(title: Text("Error"), message: Text($viewModel.productError.wrappedValue?.localizedDescription ?? ""), dismissButton: .default(Text("OK")))
}
}
}
The app works fine but When I run above code with debugger the viewModel.fetchProducts() is called three times which is surprising as I have only used it once. Can someone please suggest how can I improve it?