I am trying to have a picker that has a default value that has been passed in from a separate view. The data is being passed through, however, is not being displayed (the picker isn't being displayed either).
PickerView (the code for the picker and how data is being fetched):
struct PickerView: View {
@StateObject var MarketplaceModel = MarketplaceViewModel()
@StateObject var FavouriteProductsModel = FavouriteProductsViewModel()
var body: some View {
VStack {
Picker("Select a product", selection: $selection) {
ForEach(MarketplaceModel.products){ product in
Text(product.product_name ?? "")
}
.onAppear{
selection = selection
}
}
.pickerStyle(.menu)
// The variable 'selection' here is being outputted
Text("Selected product: \(selection)")
}
.onAppear(perform: {
let defaults = UserDefaults.standard
let stringOne = defaults.string(forKey: "key")!
self.MarketplaceModel.fetchProductData(key: stringOne)
self.FavouriteProductsModel.fetchFavouriteProducts(key: stringOne ?? "")
})
}
}
FavouriteProducts View:
struct FavouriteProducts: View {
@StateObject var MarketplaceModel = MarketplaceViewModel()
@StateObject var FavouriteProductsModel = FavouriteProductsViewModel()
var body: some View {
VStack {
ForEach(FavouriteProductsModel.favourite_products){ items in
PickerView(selection: items.product_name ?? "")
}
}
.onAppear(perform: {
let defaults = UserDefaults.standard
let stringOne = defaults.string(forKey: "key")!
self.MarketplaceModel.fetchProductData(key: stringOne)
self.FavouriteProductsModel.fetchFavouriteProducts(key: stringOne ?? "")
})
}
}
The data is being put into an array in the ViewModels (when fetched from database) In this case:
'products' & 'favourite_products'