0

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.

GarethPrice
  • 1,072
  • 2
  • 14
  • 25
  • If it's in `ContentView`, why do you need it to be triggered on appear? Can you please provide some context on what is it that you're trying to achieve? Maybe there's a better way of implementing it. – ela16 Sep 24 '22 at 13:37
  • Why does it matter if its in `ContentView`? I'd like to fetch data (`fetchEntries`) and provide that to the `ChartView`, whenever the user loads this view. – GarethPrice Sep 24 '22 at 13:55
  • Since `ContentView` is the first view to load? – ela16 Sep 24 '22 at 14:57
  • I don't understand, how does that affect whether the function in `onAppear` is able to change state or not? – GarethPrice Sep 24 '22 at 18:01

1 Answers1

0

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.

GarethPrice
  • 1,072
  • 2
  • 14
  • 25