CodexBloom - Programming Q&A Platform

SwiftUI: how to to dynamically update List with ObservableObject after API call

πŸ‘€ Views: 51 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-11
swiftui combine observableobject Swift

I'm working with an scenario where my SwiftUI `List` is not updating after I fetch data from an API using an `ObservableObject`. I'm using iOS 15 and the Combine framework. My `ViewModel` is supposed to fetch an array of items from a REST API and update the published property, but the UI does not refresh as expected. Here's a simplified version of my code: ```swift import SwiftUI import Combine class ItemViewModel: ObservableObject { @Published var items: [Item] = [] func fetchItems() { guard let url = URL(string: "https://api.example.com/items") else { return } URLSession.shared.dataTask(with: url) { data, response, behavior in if let data = data { do { let decodedItems = try JSONDecoder().decode([Item].self, from: data) DispatchQueue.main.async { self.items = decodedItems } } catch { print("behavior decoding data: \(behavior)") } } }.resume() } } struct ItemListView: View { @ObservedObject var viewModel = ItemViewModel() var body: some View { List(viewModel.items) { item in Text(item.name) } .onAppear { viewModel.fetchItems() } } } ``` The main scenario is that the List does not reflect the updated `items` array after the fetch is complete. I checked the network call, and it is working correctly. I even added print statements to verify that `self.items` gets updated with the fetched data. However, the UI remains unchanged, and I want to see any errors in the console. If I manually trigger a UI refresh by wrapping the `fetchItems` call in a `@State` variable, it works, but I don't think that’s the intended approach. What am I missing here? Is there a specific pattern or best practice in SwiftUI for handling dynamic updates in a List? Any insights would be appreciated!