Post

Replies

Boosts

Views

Activity

Reply to NavigationLink on item from Query results in infinite loop
I ran into a similar problem. It seems if a NavigationStack is placed in the parent view of a child view with a @Query with predicate, the child view will get invalidated when navigating to or back from the destination view. It seems if the destination View also references the model, that too will get invalidated leading to it navigating back before trying to navigate to the new item leading to a loop. I managed to work around it a couple ways, but the simplest is adding a dummy intermediate View between the View with the NavigationStack and the one with the @Query with predicate like this: struct ContentView: View { var body: some View { NavigationStack { DummyView() } } } struct DummyView: View { var body: some View { ListsView() } } struct ListsView: View { @Environment(\.modelContext) private var modelContext @Query(filter: #Predicate<Item> { _ in true }) // ... }
May ’24
Reply to Spurious View invalidation with NavigationStack and @Query with a predicate
I seem to have come up with a workaround. Placing a View between the View containing the NavigationStack and the one containing the @Query with predicate filter appears to solve the problem. The view graph no longer gets invalidated when clicking to navigate away or back. The resulting code looks like this: struct ContentView: View { var body: some View { NavigationStack { let _ = Self._printChanges() MiddleView() .navigationDestination(for: Item.self) { item in Text("Item at \(item.num)") } } } } struct MiddleView: View { var body: some View { let _ = Self._printChanges() SubView() } } struct SubView: View { @Environment(\.modelContext) private var modelContext @Query(filter: #Predicate<Item> { item in item.num < 20 }, sort: \.num) private var items: [Item] var body: some View { let _ = Self._printChanges() List { ForEach(items) { item in NavigationLink(value: item) { Text("Item \(item.num)") }.background(Color.random()) } } } } Not only that, but it appears that using NavigationLink(destination:, label: ) in the SubView seems to work now as well whereas before it would sometimes cause an infinite loop when navigating from a view with a Query predicate to another view with one.
May ’24