Hello,
I have a question regarding the task(id:) modifier. It is possible, of course, that I am using the modifier for the wrong purpose.
Consider a multi-field search scenario where any change to a field triggers a loading process via the task(id:) modifier.
The problem is that every task(id:) modifier executes when the view is first loaded, causing the same data to be loaded multiple times—which makes no sense. I do not want to add a separate search button or implement debouncing; those would merely be workarounds to bypass the actual issue.
The onChange modifier has an initial parameter that defaults to false, preventing the action from running when the view is first loaded. However, the task(id:) modifier does not have this parameter.
How can I prevent all task(id:) modifiers from executing when the view loads? After all, the standard task modifier should handle the initial load.
struct ContentView: View {
@State private var field1: String = ""
@State private var field2: String = ""
@State private var field3: String = ""
var body: some View {
VStack {
TextField("val1", text: $field1)
TextField("val2", text: $field2)
TextField("val3", text: $field3)
}
.padding()
.task {
print("task")
}
.task(id: field1) {
print("task 1")
}
.task(id: field2) {
print("task 2")
}
.task(id: field3) {
print("task 3")
}
}
}
Christian