swiftstateonappear

OnAppear does not update State, button action does


In a ContentView(), I have a the below:


@State var entries = [AType]()

var body: some View {
        NavigationView {
            List {
                if self.entries.count == 0 {
                    Button {
                        loadChartData()
                    } label: {
                        Text("Load data")
                    }

                } else {
                    Section {
                        ChartView(entries: self.entries).frame(height: 150).padding()
                    }
                }
            }
            .navigationTitle("My Title")
            .onAppear {
                loadChartData()
            }
        }
    }
    
    func loadChartData() {
        MyController.shared.fetchEntries { result in
            switch result {
                case .success(let entries):
                    self.entries = entries.data
                case .failure(let error):
                    print(error)
            }
        }
    }
}

The button action works, and modifies the state appropriately, showing the ChartView, however the onAppear part doesn't. I've tried putting this in a Dispatch.main.async() call, and also used .task {} instead of .onAppear{}, but nothing seems to make any difference.

Any help would be much appreciated.


Solution

  • I fixed this by using @Published on a instance variable in the MyController class, and then using a @ObservedObject variable in the ContentView struct. Lastly, a function is called by onAppear in ContentView that updates the @Published variable in the controller, which then re-renders the ContentView.