Most Optimal Way To Fetch Data In A SwiftUI View Once?

I wish to ask for suggestions how to go about how to fetch data once it is successful in a swift ui view.

Where is it best to put it? What annotation is best suited for this?

I have a map view and it fetches data first before showing marker annotations. I put it in onAppear. This may work if it is just 1 view. But if this view is used inside a TabView, then once the tab is selected, the onAppear block will be executed and will be fetched again.

What is the best way to go about this by fetching the data only once? Thoughts?

var body: some View {
    TabView {
      MapView(cameraUpdate: ...)
      .onAppear() {         
         // fetch data here.
      }
      .onDisappear() {
         
      }
      .tabItem {
        Label("tab2, systemImage: "list.dash")
      }
     
      MapView(cameraUpdate: ...)
      .onAppear() {         
         
      }
      .onDisappear() {
         
      }
      .tabItem {
        Label("tab2, systemImage: "list.dash")
      }
    }
    .onAppear() {
       
    }
  }
Answered by Claude31 in 732417022

You could set a State var (or Binding var, depend how your code is structured) to keep track that loaded is completed.

Then in .onAppear, use this var as a condition to fetch data.

Accepted Answer

You could set a State var (or Binding var, depend how your code is structured) to keep track that loaded is completed.

Then in .onAppear, use this var as a condition to fetch data.

Most Optimal Way To Fetch Data In A SwiftUI View Once?
 
 
Q