Child view not rendering when adding @Query macro – Infinite loop

For some reason when I add an @Query macro to my child view it fails to render. If I simplify my child view by just adding a plain text field while still leaving the @Query macro it still won’t render. However, if I comment out the @Query macro in the child view then it renders, why?

I have been scratching my head trying to figure that out. I’d love to be able to use the album’s id that is being passed from the parent view in the child view to filter the @Query for the media, but I haven’t been able to figure out how to do that either since I can’t view my child view if it uses the @Query macro. I feel like it may be stuck in a loop or something. FYI, I only have about 30 rows of media in the database so it isn’t large or anything. Also, if I add logging to the child view using the .onAppear modifier it does output logs even though the view isn’t shown.

Side note, the preview for the child view works fine, just not when navigating to it from the parent view.

Here are my SwiftData models:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import SwiftUI
import SwiftData
@Model
class Album: Identifiable {
var id: UUID = UUID()
var isPublicAlbum: Bool = false
var title: String = ""
var timeStamp: Date = Date()
@Relationship(deleteRule: .cascade, inverse: Media.album) var media: [Media]?
init(isPublicAlbum: Bool, title: String, timeStamp: Date = Date()) {
self.isPublicAlbum = isPublicAlbum
self.title = title
self.timeStamp = timeStamp
}
}
import SwiftUI
import SwiftData
@Model
class Media: Identifiable {
var id: UUID = UUID()
var albumID: UUID = UUID()
var timeStamp: Date = Date()
//var album: Album?
@Relationship(deleteRule: .nullify) var album: Album?
init(albumID: UUID = UUID(), timeStamp: Date = Date()) {
self.albumID = albumID
self.timeStamp = timeStamp
}
}
</code>
<code>import SwiftUI import SwiftData @Model class Album: Identifiable { var id: UUID = UUID() var isPublicAlbum: Bool = false var title: String = "" var timeStamp: Date = Date() @Relationship(deleteRule: .cascade, inverse: Media.album) var media: [Media]? init(isPublicAlbum: Bool, title: String, timeStamp: Date = Date()) { self.isPublicAlbum = isPublicAlbum self.title = title self.timeStamp = timeStamp } } import SwiftUI import SwiftData @Model class Media: Identifiable { var id: UUID = UUID() var albumID: UUID = UUID() var timeStamp: Date = Date() //var album: Album? @Relationship(deleteRule: .nullify) var album: Album? init(albumID: UUID = UUID(), timeStamp: Date = Date()) { self.albumID = albumID self.timeStamp = timeStamp } } </code>
import SwiftUI
import SwiftData

@Model
class Album: Identifiable {
    var id: UUID = UUID()
    var isPublicAlbum: Bool = false
    var title: String = ""
    var timeStamp: Date = Date()
    
    @Relationship(deleteRule: .cascade, inverse: Media.album) var media: [Media]?
    
    init(isPublicAlbum: Bool, title: String, timeStamp: Date = Date()) {
        self.isPublicAlbum = isPublicAlbum
        self.title = title
        self.timeStamp = timeStamp
    }
}

import SwiftUI
import SwiftData

@Model
class Media: Identifiable {
    var id: UUID = UUID()
    var albumID: UUID = UUID()
    var timeStamp: Date = Date()
    //var album: Album?
    
    @Relationship(deleteRule: .nullify) var album: Album?
    
    init(albumID: UUID = UUID(), timeStamp: Date = Date()) {
        self.albumID = albumID
        self.timeStamp = timeStamp
    }
}

Here is my model container:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import SwiftData
class ModelContainerManager {
static let shared = ModelContainerManager()
let container: ModelContainer
private init() {
do {
container = try ModelContainer(for: User.self, Album.self, Media.self)
} catch {
fatalError(error.localizedDescription)
}
}
}
</code>
<code>import SwiftData class ModelContainerManager { static let shared = ModelContainerManager() let container: ModelContainer private init() { do { container = try ModelContainer(for: User.self, Album.self, Media.self) } catch { fatalError(error.localizedDescription) } } } </code>
import SwiftData

class ModelContainerManager {
    static let shared = ModelContainerManager()
    let container: ModelContainer

    private init() {
        do {
            container = try ModelContainer(for: User.self, Album.self, Media.self)
        } catch {
            fatalError(error.localizedDescription)
        }
    }
}

I pass my container to all my views like so:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>WindowGroup {
//...
}
.modelContainer(ModelContainerManager.shared.container)
</code>
<code>WindowGroup { //... } .modelContainer(ModelContainerManager.shared.container) </code>
WindowGroup {
    //...
}
.modelContainer(ModelContainerManager.shared.container)

Here is the relevant code for my parent view:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>struct MainView: View {
@Environment(.modelContext) private var dbContext
@Environment(.horizontalSizeClass) var horizontalSizeClass
@Environment(.colorScheme) var colorScheme
@Query(filter: #Predicate<Album> { $0.isPublicAlbum == false }, sort: Album.title, order: .forward) private var listAlbums: [Album]
@State private var searchString: String = ""
private var filteredAlbums: [Album] {
if searchString.isEmpty {
return listAlbums
} else {
return listAlbums.filter { album in
album.title.localizedStandardContains(searchString)
}
}
}
//...
var body: some View {
VStack {
CustomSearchBar(text: $searchString, placeholder: NSLocalizedString("Search Albums", comment: "This is a search bar to search for albums"))
//...
ForEach(filteredAlbums) { album in
VStack(spacing: 0) {
ZStack(alignment: .topTrailing) {
NavigationLink(destination: PersistentAlbumView(album: album)) {
//...
}
}
}
}
//...
}
}
}
</code>
<code>struct MainView: View { @Environment(.modelContext) private var dbContext @Environment(.horizontalSizeClass) var horizontalSizeClass @Environment(.colorScheme) var colorScheme @Query(filter: #Predicate<Album> { $0.isPublicAlbum == false }, sort: Album.title, order: .forward) private var listAlbums: [Album] @State private var searchString: String = "" private var filteredAlbums: [Album] { if searchString.isEmpty { return listAlbums } else { return listAlbums.filter { album in album.title.localizedStandardContains(searchString) } } } //... var body: some View { VStack { CustomSearchBar(text: $searchString, placeholder: NSLocalizedString("Search Albums", comment: "This is a search bar to search for albums")) //... ForEach(filteredAlbums) { album in VStack(spacing: 0) { ZStack(alignment: .topTrailing) { NavigationLink(destination: PersistentAlbumView(album: album)) { //... } } } } //... } } } </code>
struct MainView: View {
    @Environment(.modelContext) private var dbContext
    @Environment(.horizontalSizeClass) var horizontalSizeClass
    @Environment(.colorScheme) var colorScheme
    @Query(filter: #Predicate<Album> { $0.isPublicAlbum == false }, sort: Album.title, order: .forward) private var listAlbums: [Album]
    @State private var searchString: String = ""
    
    private var filteredAlbums: [Album] {
        if searchString.isEmpty {
            return listAlbums
        } else {
            return listAlbums.filter { album in
                album.title.localizedStandardContains(searchString)
            }
        }
    }

    //...

    var body: some View {
        VStack {
            CustomSearchBar(text: $searchString, placeholder: NSLocalizedString("Search Albums", comment: "This is a search bar to search for albums"))
            //...
            ForEach(filteredAlbums) { album in
                VStack(spacing: 0) {
                    ZStack(alignment: .topTrailing) {
                        NavigationLink(destination: PersistentAlbumView(album: album)) {
                            //...
                        }
                    } 
                }
            }
            //...
        }
    }
}

Here is my child view:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import SwiftUI
import SwiftData
struct PersistentAlbumView: View {
@Environment(.modelContext) private var dbContext
@Query private var mediaItems: [Media]
let album: Album
var body: some View {
VStack {
if !mediaItems.isEmpty {
List(mediaItems) { item in
if item.albumID == album.id {
Text("Media ID: (item.id.uuidString)")
}
}
} else {
Text("No media found")
}
}
}
}
#Preview {
NavigationStack {
PersistentAlbumView(album: PreviewContainer.getAlbum(at: 3))
.modelContainer(PreviewContainer.container)
.navigationBarTitleDisplayMode(.inline)
}
}
</code>
<code>import SwiftUI import SwiftData struct PersistentAlbumView: View { @Environment(.modelContext) private var dbContext @Query private var mediaItems: [Media] let album: Album var body: some View { VStack { if !mediaItems.isEmpty { List(mediaItems) { item in if item.albumID == album.id { Text("Media ID: (item.id.uuidString)") } } } else { Text("No media found") } } } } #Preview { NavigationStack { PersistentAlbumView(album: PreviewContainer.getAlbum(at: 3)) .modelContainer(PreviewContainer.container) .navigationBarTitleDisplayMode(.inline) } } </code>
import SwiftUI
import SwiftData

struct PersistentAlbumView: View {
    @Environment(.modelContext) private var dbContext
    @Query private var mediaItems: [Media]
    let album: Album
    
    var body: some View {
        VStack {
            if !mediaItems.isEmpty {
                List(mediaItems) { item in
                    if item.albumID == album.id {
                        Text("Media ID: (item.id.uuidString)")
                    }
                }
            } else {
                Text("No media found")
            }
        }
    }
}

#Preview {
    NavigationStack {
        PersistentAlbumView(album: PreviewContainer.getAlbum(at: 3))
            .modelContainer(PreviewContainer.container)
            .navigationBarTitleDisplayMode(.inline)
    }
}

I have tested the following simplified view by using it outside of the parent view to make sure the media query does work, and it does:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import SwiftUI
import SwiftData
struct MediaListView: View {
@Query private var mediaItems: [Media]
var body: some View {
List(mediaItems, id: .id) { media in
Text(media.id.uuidString)
}
}
}
#Preview {
MediaListView()
.modelContainer(PreviewContainer.container)
}
</code>
<code>import SwiftUI import SwiftData struct MediaListView: View { @Query private var mediaItems: [Media] var body: some View { List(mediaItems, id: .id) { media in Text(media.id.uuidString) } } } #Preview { MediaListView() .modelContainer(PreviewContainer.container) } </code>
import SwiftUI
import SwiftData

struct MediaListView: View {
    @Query private var mediaItems: [Media]
    
    var body: some View {
        List(mediaItems, id: .id) { media in
            Text(media.id.uuidString)
        }
    }
}

#Preview {
    MediaListView()
        .modelContainer(PreviewContainer.container)
}

If anyone can tell me what in the world I’m doing wrong that would be awesome!

P.S. I don’t want to use album.media since it is a relation and is treated like a computed property. When using album.media, the view doesn’t show updates in real-time when the app is reinstalled and new data has been synced with my Media model. So using the relationship is not an option for me.

Any help on fixing the @Query macro in my child view to use it on my Media model would be awesome! I usually can figure out stuff like this but I’m not used to working with SwiftData. Thanks in advance!

2

I spent over a week tinkering with this issue here and there as I had time and oddly enough I was able to figure out the issue after posting my question. Instead of deleting the question, I thought I would share the solution and problem to help others avoid this huge headache when using SwiftData @Query macros in multiple child views.

The issue was indeed an infinite loop that is caused when you have multiple child views nested in a parent NavigationStack and you use the NavigationLink to render those child views that are using additional @Query macros.

The solution for me was to first create a new struct inside the parent view that uses the first @Query macro and then render the child view that will use the second @Query macro from there.

Example based on my original post:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import SwiftUI
import SwiftData
struct MainView: View {
@Query(filter: #Predicate<Album> { $0.isPublicAlbum == false }, sort: Album.title, order: .forward) private var listAlbums: [Album]
//...
NavigationLink(destination: RenderAlbumView(album: album)) {
//...
}
}
//...
// Fixes NavigationStack @Query infinite loop issue
struct RenderAlbumView: View {
let album: Album
var body: some View {
PersistentAlbumView(album: album)
}
}
</code>
<code>import SwiftUI import SwiftData struct MainView: View { @Query(filter: #Predicate<Album> { $0.isPublicAlbum == false }, sort: Album.title, order: .forward) private var listAlbums: [Album] //... NavigationLink(destination: RenderAlbumView(album: album)) { //... } } //... // Fixes NavigationStack @Query infinite loop issue struct RenderAlbumView: View { let album: Album var body: some View { PersistentAlbumView(album: album) } } </code>
import SwiftUI
import SwiftData

struct MainView: View {
    @Query(filter: #Predicate<Album> { $0.isPublicAlbum == false }, sort: Album.title, order: .forward) private var listAlbums: [Album]

    //...

    NavigationLink(destination: RenderAlbumView(album: album)) {
        //...
    }
}

//...

// Fixes NavigationStack @Query infinite loop issue
struct RenderAlbumView: View {
    let album: Album
    
    var body: some View {
        PersistentAlbumView(album: album)
    }
}
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import SwiftUI
import SwiftData
struct PersistentAlbumView: View {
@Environment(.modelContext) private var dbContext
@Query(sort: Media.timeStamp, order: .forward) private var mediaItems: [Media]
let album: Album
// Using an initializer to filter only the data that is needed.
init(album: Album) {
self.album = album
let albumID = album.id
_mediaItems = Query(
filter: #Predicate<Media> { $0.albumID == albumID }
)
}
//...
}
</code>
<code>import SwiftUI import SwiftData struct PersistentAlbumView: View { @Environment(.modelContext) private var dbContext @Query(sort: Media.timeStamp, order: .forward) private var mediaItems: [Media] let album: Album // Using an initializer to filter only the data that is needed. init(album: Album) { self.album = album let albumID = album.id _mediaItems = Query( filter: #Predicate<Media> { $0.albumID == albumID } ) } //... } </code>
import SwiftUI
import SwiftData

struct PersistentAlbumView: View {
    @Environment(.modelContext) private var dbContext
    @Query(sort: Media.timeStamp, order: .forward) private var mediaItems: [Media]
    let album: Album

    // Using an initializer to filter only the data that is needed.
    init(album: Album) {
        self.album = album
        
        let albumID = album.id
        _mediaItems = Query(
            filter: #Predicate<Media> { $0.albumID == albumID }
        )
    }

    //...
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật