1

I want to load health data so that when the tab is tapped a users steps are displayed once. But by using onAppear, every time the tab is tapped it loads the steps again and displays them twice. I believe this is due to the onAppear. What alternative should be used here?

struct StepPreview: View {
    
    var body: some View {
        
    NavigationView {
        
        ScrollView {
            
            LazyVStack{
        
            ForEach(steps, id: \.id) { step in
                
                VStack(spacing: 15){
                    Text("\(step.count)")
                        .font(.custom(customFont, size: 100))
                        .fontWeight(.semibold)
                        .multilineTextAlignment(.center)
                        .opacity(5)
                        .aspectRatio(contentMode: .fill)
                        .frame(width: 200, height: 200)
                        .padding(.bottom, -45)
            }
        }
    }
    .onAppear {
        if let healthStore = healthStore {
            healthStore.requestAuthorization { success in
                if success {
                    healthStore.calculateSteps { statisticsCollection in
                        if let statisticsCollection = statisticsCollection {
                            // update the UI
                            updateUIFromStatistics(statisticsCollection)
                        }
                    }
                }
            }
        }
    }
    }
}
Mxyb
  • 83
  • 1
  • 9
  • 6
    Create a StateObject for the View and do the work in there. You can use the init for the initial setup. The View should be unconcerned of the source of what it is displaying. – lorem ipsum Feb 25 '22 at 13:12
  • Okay I see, I've created a StateObject for the view but am unsure on how to initialise it. When I try init, I get an error that says "Cannot assign property: theHealthStore is a get-only property" – Mxyb Feb 25 '22 at 15:58
  • 1
    Please take the [tour](https://stackoverflow.com/tour) and read [How to Ask](https://stackoverflow.com/help/how-to-ask) to improve, edit and format your questions. Without a [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) it is impossible to help you troubleshoot. – lorem ipsum Feb 25 '22 at 16:00

0 Answers0