Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List ForEach not updating correctly

I am using Core data and Swiftui and everything have been working fine but in this one view I have a List, ForEach that is not working.

So for testing purpose my code currently look like this:


@ObservedObject var viewModel = NewLearningWhyViewModel()

VStack {
    ForEach(viewModel.whys, id: \.self) { why in
        Text(why.why)
    }
            
    List {
        ForEach(viewModel.whys, id: \.self) { why in
            Text(why.why)
        }
    }
           
    Button(action: {
        viewModel.createWhy(why: "Test", count: viewModel.whys.count, learning: learn)
        viewModel.fetchWhy(predicate: NSPredicate(format: "parentLearning == %@", learn))
    }){
        Text("Add")
            .font(.title)
            .foregroundColor(.white)
    }
}            

The problem is my List { ForEach, first time I press add button it shows the new why, second time i press the button the whole list goes away, the third time I press the button the list shows again with all 3 items.

To test the problem I added that first ForEach part and that shows the correct item at all times, so there is not a problem with the viewmodel or adding the items, the items are added and it is published from the viewmodel since that part is updated.

Does anyone have any clue why my List { ForEach only show every other time?

like image 604
Peter Avatar asked Dec 13 '25 02:12

Peter


1 Answers

I have gotten this problem. I figure it out by adding objectWillChange in ViewModel, and send() it manually when your why is changed. Actually I don't know your NewLearningWhyViewModel clearly, so this is just an example, you should try it out.

class NewLearningWhyViewModel: ObservableObject {
    let objectWillChange: ObservableObjectPublisher = ObservableObjectPublisher()
    @Published var whys: Why = Why() {
        didSet {
            objectWillChange.send()
        }
    }
}
like image 166
Ho Si Tuan Avatar answered Dec 15 '25 14:12

Ho Si Tuan