swiftuiswiftdataswift-data-modelcontext

View is not updated after modelContext.delete(item)


import SwiftUI
import SwiftData

struct ItemListView: View {
    @Bindable var luggage: Luggage
    @Environment(\.modelContext) var modelContext
    @State private var selectedItem: Item?
    
    var body: some View {
        List {
            ForEach(luggage.items) { item in
                ItemListRow(item: item)
                    .swipeActions(edge: .trailing, allowsFullSwipe: true) {
                        Button {
                           modelContext.delete(item)
                        } label: {
                            Image(systemName: "trash")
                        }
                        .tint(.red)
                        
                        Button {
                            selectedItem = item
                        } label: {
                            Image(systemName: "pencil")
                        }
                        .tint(.orange)
                    }
            }

When I do a swipe action to delete my item in a list, SwiftUI is not updating the list. It is deleted when I force quit the app and relaunch it...


Solution

  • Assuming Luggage is a @Model class returned from a SwiftData query,

    try replacing modelContext.delete(item) with

      if let index = luggage.items.firstIndex(of: item) {
          luggage.items.remove(at: index)
      }
    

    Since @Model class conforms to observable, the app/system will use its autosave feature, and SwiftData automatically saves the changes for you. No need to call the model context in this particular case.