swiftuicloudkitswiftdata

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:

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:

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:

WindowGroup {
    //...
}
.modelContainer(ModelContainerManager.shared.container)

Here is the relevant code for my parent view:

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:

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:

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 relationship 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!


Solution

  • 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 first to create a new struct and call it from the parent view that uses the first @Query macro and then render the child view that will use the second @Query macro from the new struct.

    Example based on my original post:

    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)
        }
    }
    
    import SwiftUI
    import SwiftData
    
    struct PersistentAlbumView: View {
        @Environment(\.modelContext) private var dbContext
        @Query 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 },
                sort: \Media.timeStamp, order: .reverse
            )
        }
    
        //...
    }