SwiftUI Warning: Update NavigationAuthority bound path tried to update multiple times per frame

42 Views Asked by At

I have a warning “Update NavigationAuthority bound path tried to update multiple times per frame.” when I click “Add Item”. This warning doesn’t show after the elements are in the list. It only happened after I added the logic with path = [newItem]. I’m not sure what I’m missing. Here is my code:

import SwiftUI
import SwiftData

struct ContentView: View {
    @Environment(\.modelContext) private var modelContext
    @Query private var items: [Item]
    @State private var path = [Item]()
    
    var body: some View {
        NavigationStack  (path: $path) {
            List {
                ForEach(items) { item in
                    NavigationLink (value: item) {
                        Text("Some label text")
                    }
                }
                .onDelete(perform: deleteItems)
            }
            
            .navigationDestination(for: Item.self, destination: EditItemView.init)

            .toolbar {
                ToolbarItem {
                    Button(action: addItem) {
                        Label("Add Item", systemImage: "plus")
                    }
                }
            }
        }
    }

    private func addItem() {
        withAnimation {
            let newItem = Item(timestamp: Date())
            modelContext.insert(newItem)
            path = [newItem]
            
        }
    }

    private func deleteItems(offsets: IndexSet) {
        withAnimation {
            for index in offsets {
                modelContext.delete(items[index])
            }
        }
    }
}

struct EditItemView: View {
    
    @Bindable var item: Item
    
    var body: some View {
        Text("Item at \(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))")
            .navigationTitle("Edit Item")
    }
}


@Model
final class Item {
    var timestamp: Date

    init(timestamp: Date) {
        self.timestamp = timestamp
    }
}
0

There are 0 best solutions below