0

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
Devbot10
  • 1,193
  • 18
  • 33
  • see https://stackoverflow.com/questions/63080830/swifui-onappear-gets-called-twice seems to be a SwiftUI Bug. fun fact: if you replace `List` with `ScrollView` it seems to work as expected. Some said it has been fixed with iOS 15.1 but actually they haven't fixed everything – Daniel Marx Jan 14 '22 at 10:33

0 Answers0