How to call swiftdata .fetch inside the Init of a SwiftUI View?

I have a list of swiftdata objects I want to fetch and show in a swift UI list. My problem is the swiftdata object in my DB is not the object I directly want to use in my view. I want to map it to a different viewModel and use that which makes my life wayyy easier.

problem is every single example I see online of swift data, just uses the magic @Query operator to get their data, and then directly show it on the UI.

What's the best way for me to load the data on initialization but map it to a different type? I've tried this, but it just crashes.


init() {
     do {
            modelContainer = try ModelContainer(for: MY_DATA_CLASS.self)
       } catch {
             fatalError("Could not initialize ModelContainer")
        }

    let serverList = FetchDescriptor<MY_DATA_CLASS>(
        sortBy: [SortDescriptor(\.displayOrder)]
    )

    do {
        viewModels =  try modelContext.fetch(serverList).map {
            ViewModel(server: $0)
        }
    } catch {
        print(" WHAT THE HECKKK: " + error.localizedDescription)
    }

 }

NSFetchRequest could not locate an NSEntityDescription for entity name ....

any suggestions greatly appreciated. Using @query works fine so I know the rest of the DB is setup correctly.

Answered by eclair4151 in 761547022

after more debugging, calling the code inside onappear instead of init seems to have solved the issue

I also tried

let servers = Query(FetchDescriptor<MY_DATA_CLASS>()).wrappedValue

but get the error

Set a .modelContext in view's environment to use Query

I have this in the top of the class, but I assume it hasnt been initialized yet?

@Environment(\.modelContext) private var modelContext
Accepted Answer

after more debugging, calling the code inside onappear instead of init seems to have solved the issue

How to call swiftdata .fetch inside the Init of a SwiftUI View?
 
 
Q