SwiftUI: What is an alternative to using onAppear?

927 views Asked by At

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)
                        }
                    }
                }
            }
        }
    }
    }
}
0

There are 0 answers