I am facing an issue where the view does not update automatically with the @Observable object.
struct Person: Identifiable {
var id: Int
var name: String
init(id: Int, name: String){
self.id = id
self.name = name
}
}
class People: ObservableObject {
@Published var people: [Person]
@Published var kitchens: [Kitchen]
init(){
self.people = [
Person(id: 1, name:"Javier"),
Person(id: 2, name:"Juan"),
Person(id: 3, name:"Pedro")]
}
}
struct ContentView: View {
@ObservedObject var mypeople: People
var body: some View {
VStack{
ForEach(mypeople.people){ person in
Text("\(person.name)")
}
Button(action: {
self.mypeople.people.append(Person(id: 7, name: "New person"))
}) {
Text("Add/Change name")
}
}.onAppear {
self.mypeople.people.append(Person(id: 7, name: "New person"))
}
}
}
So, what I want to do is that I have to add a new person, in onAppear instead of adding a new person on tap of the button. In short, the people array lets say, already has three persons and I have to add the fourth one just while landing on that view.
The weird thing is that person gets added if this view if the root view, however, it does not work when this view is pushed using Navigation Link. In the second case, a new person is added and removed right away keeping the people array count to three.
However, the new person easily gets added on the tap of the button. I am stuck here for several hours. Any help would be more than appreciated!! Thanks in Advance!
EDIT
I debugged little more to find out the issue. So, the new person is added in the below scenarios automatically in onAppear:
1) If the ContentView is the root view of the application. 2) If the ContentView is pushed from the very first view in the hierarchy of the parent view. Means, if there are subViews of the ContentView. The Navigation Link from the subViews creates this problem, however, the navigation link directly from the ContentView adds the person successfully.
And for creating a navigationLink, I used:
NavigationLink(destination: ContentView()) {
Text("View All")
}