CodexBloom - Programming Q&A Platform

SwiftUI: how to to Refresh List After Updating ViewModel in iOS 17

👀 Views: 85 💬 Answers: 1 📅 Created: 2025-06-11
swift swiftui list

I'm writing unit tests and I need help solving I'm experiencing an scenario where a SwiftUI `List` does not refresh after I update my ViewModel... I have a ViewModel that holds a list of items fetched from an API. When I update the list, the UI does not reflect these changes, despite the data model being updated correctly. I'm using `@Published` properties in my ViewModel and the `List` is supposed to react to these changes. The relevant code snippet for my ViewModel is as follows: ```swift import Combine class ItemViewModel: ObservableObject { @Published var items: [Item] = [] func fetchItems() { // Simulated API call DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.items = [Item(name: "Item 1"), Item(name: "Item 2")] } } func updateItems() { // Simulated update DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.items.append(Item(name: "Item 3")) } } } ``` And my SwiftUI view looks like this: ```swift import SwiftUI struct ItemListView: View { @StateObject private var viewModel = ItemViewModel() var body: some View { List(viewModel.items, id: \ .name) { item in Text(item.name) } .onAppear { viewModel.fetchItems() } .toolbar { Button("Add Item") { viewModel.updateItems() } } } } ``` Upon tapping the "Add Item" button, the `updateItems` method is called, and I can see that the `items` property is updated. However, the `List` does not refresh to show the new item. I've confirmed that the ViewModel is still being observed and that the `items` property changes correctly by printing the contents of `items` after the update. I’ve tried using `@ObservedObject` instead of `@StateObject`, but that didn’t resolve the scenario either. Is there something I’m missing regarding state management in SwiftUI or how `List` interacts with `@Published` properties? Any insights would be greatly appreciated! I'm working in a Debian environment. Any help would be greatly appreciated! This issue appeared after updating to Swift 3.9.