Search code examples
swiftswiftdata

wait for context to be updated when using SwiftData


How would you wait for the context to be updated before continuing?

import SwiftData
@State var selectedItem: Item?
@Query var items: [Item]

    func addItem() {
        let item = Item()
        context.insert(item)
        selectedItem = item
        print(items)
    }

result: []

desired: [Item]

    func deleteItem(at offsets: IndexSet) {
        for index in offsets {
            context.delete(items[index])
        }
        if items.isEmpty || items.contains(where: { $0.id == selectedItem?.id }) == false {
            selectedItem = nil
        }
    }

since the context isn't updated at the time of the if statement, it never runs as expected.


Solution

  • Why not get hold of the index of the selected item first and clear the selection if it's part of the deleted objects.

    if let selectedIndex = items.firstIndex(where { $0.id == selectedItem?.id }, offsets.contains(selectedIndex) {
        selectedItem = nil
    } 
    
    // delete loop...