swiftswiftuionappear

OnAppear only once the view is opened


I want to update the view with data when a view is opened so I added:

.onAppear {
    loadData()
}

But I only want to update it once when the view gets opened not every time it gets reopened e.g. with a back button.

--> Only update on App start


Solution

  • struct ContentView: View {
        @State private var firstTime = true
        var body: some View {
            VStack {
            
            }
            .onAppear(){
                if firstTime {
                    // this is the first time app did start
                    loadData()
                    firstTime = false
                }
            }
        }
    }