I have a very simple application / navigation and for some reason .task{}
and .onAppear{}
are both being called twice. I was under the assumption that onAppear
was generally a good place to fetch initial data which recently got replaced by .task
, which allows for async/await
. Is this a SwiftUI bug? Obviously I don't want to fetch initial data twice.
import SwiftUI
struct ContentView: View {
var body: some View {
TabView {
NavigationView {
TestView()
}
}
.onAppear {
print("Test: onAppear TabView")
}
.task {
print("Test: task TabView")
}
}
}
struct TestView: View {
let count = 10
var body: some View {
List {
ForEach(0..<count) { _ in
Text("1")
}
}
.onAppear {
print("Test: List on Appear")
}
.task() {
print("Test: List Task called")
//await viewModel.fetchData()
}
}
}
This is the console output:
Test: onAppear TabView
Test: List on Appear
Test: List on Appear
Test: task TabView
Test: List Task called
Test: List Task called