I'm trying to figure out how to make a SwiftUI view that displays data from SwiftData using a query that includes variables passed into the view. I'm guessing that I won't be able to use the @Query syntax, but has anyone come up with a workable method to do something like this?
Do I need to abandon the @Query and just create a view model that instantiates it's own ModelContainer and ModelContext?
This code is obviously not compiling because the @Query is referencing the startDate and endDate variables, but this is what I want.
struct MyView: View {
@Environment(\.modelContext) var modelContext
@Query(FetchDescriptor<Measurement>(predicate: #Predicate<Measurement> {
$0.date >= startDate && $0.date <= endDate }, sortBy: [SortDescriptor(\Measurement.date)])) var measurements: [Measurement]
let startDate: Date = Date.distantPast
let endDate: Date = Date.distantFuture
var body: some View {
Text("Help")
}
}
You can't have a dynamic query (not yet) but a workaround is to inject in the dates (or the full predicate) into the view and create the query that way.
@Query var measurements: [Measurement]
init(startDate: Date, endDate: Date) {
let predicate = #Predicate<Measurement> {
$0.date >= startDate && $0.date <= endDate
}
_measurements = Query(filter: predicate, sort: \.date)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With