Passing search terms down to child view queries #62
-
I'm trying to figure out the correct way of passing search terms from My code look something like this: struct BarRequest: ValueObservationQueryable {
let foo: Foo
var searchText: String = ""
static var defaultValue: [Bar] { [] }
func fetch(_ db: Database) throws -> [Bar] {
// Actually FTS but that's not relevant here
try foo.bars.filter(Column("name").like("%\(searchText)%")).fetchAll(db)
}
}
struct ParentView: View {
var foos: [Foo]
@State private var searchText: String
var body: some View {
LazyHStack {
ForEach(foos, id: \.id) {
ChildView(foo: $0).id($0.id)
}.searchable(
text: $searchText,
prompt: "Search for a thing"
)
}
}
}
struct ChildView: View {
var foo: Foo
@Query<BarRequest> private var bars: [Bar]
init(foo: Foo) {
self.foo = foo
_items = Query(BarRequest(foo: foo))
}
var body: some View {
List(childItems) { item in
Text(childItems.name)
}
}
} I'd like to pass the search terms to each child view so that they use them in their requests. This is a UI where you can swipe between the child views so I'd like to avoid setting I can do that (and it works perfectly with a binding to |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hello @matiaskorhonen,
Sure, let's do that: struct ParentView: View {
var foos: [Foo]
@State private var searchText: String
var body: some View {
LazyHStack {
ForEach(foos, id: \.id) {
- ChildView(foo: $0).id($0.id)
+ ChildView(foo: $0, searchText: searchText).id($0.id)
}.searchable(
text: $searchText,
prompt: "Search for a thing"
)
}
}
}
struct ChildView: View {
var foo: Foo
@Query<BarRequest> private var items: [Bar]
- init(foo: Foo) {
+ init(foo: Foo, searchText: String) {
self.foo = foo
- _items = Query(BarRequest(foo: foo))
+ // Use the Query initializer that makes sure
+ // new items are fetched whenever foo or searchText change.
+ _items = Query(constant: BarRequest(foo: foo, searchText: searchText))
}
var body: some View {
List(items) { item in
Text(item.name)
}
}
} Note how I use the Without this See Initializing @Query from a Constant Request in the "Adding Parameters to Queryable Types" guide. |
Beta Was this translation helpful? Give feedback.
Hello @matiaskorhonen,
Sure, let's do that: