Reputation: 11
In ContentView.swift, I have:
List(recipeData) { recipe in NavigationLink(destination: RecipeView(recipe: recipe)){
Text(recipe.name)
}
}
In the RecipeView, user might update the recipeData variable. However, when the RecipeView is closed, ContentView is not updated based on the updated recipeData.
recipeData is not a @State array but a normal one that is declared outside the ContentView struct. I cannot easily make it a @State var because it is used in other parts of the app.
Thanks!
Upvotes: 1
Views: 144
Reputation: 199
Using @ObservableObject
and @Published
you can achieve your requirements.
ViewModel
final class RecipeListViewModel: ObservableObject {
@Published var recipeData: [Recipe] = []
....
....
//write code to fetch recipes from the server or local storage and fill the recipeData
....
....
}
View
struct RepositoryListView : View {
@ObservedObject var viewModel: RecipeListViewModel
var body: some View {
NavigationView {
List(viewModel.recipeData) { recipe in
NavigationLink(destination: RecipeView(recipe: recipe)) {
Text(recipe.name)
}
}
}
}
Upvotes: 0