SPR
SPR

Reputation: 43

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

Upvotes: 0

Views: 1627

Answers (2)

Ahmed
Ahmed

Reputation: 118

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

Upvotes: 0

azamsharp
azamsharp

Reputation: 20096

You can put the value in UserDefaults so you will know in the second load that you have already performed loading.

extension UserDefaults {
    
    var firstTimeVisit: Bool {
        get {
            return UserDefaults.standard.value(forKey: "firstTimeVisit") as? Bool ?? true
        } set {
            UserDefaults.standard.setValue(newValue, forKey: "firstTimeVisit")
        }
    }
    
}

struct ContentView: View {
    
    var body: some View {
        VStack {
            
        }.task {
            if UserDefaults.standard.firstTimeVisit {
                // load Data
                UserDefaults.standard.firstTimeVisit = false
            } 
        }
    }
}

UPDATE:

extension UserDefaults {
    
    var firstTimeVisit: Bool {
        get {
            return !UserDefaults.standard.bool(forKey: "firstTimeVisit")
        } set {
            
            UserDefaults.standard.set(newValue, forKey: "firstTimeVisit")
        }
    }
    
}

Upvotes: 0

Related Questions