Home > front end >  Update EnvironmentObject value in ViewModel and then reflect the update in a View
Update EnvironmentObject value in ViewModel and then reflect the update in a View

Time:04-13

I have an environment object with the property auth in my root ContentView:

class User: ObservableObject {
    @Published var auth = false
}

My goal is to update auth to true inside of a function in my AuthViewModel:

class AuthViewModel: ObservableObject {
    
    
    var user: User = User() 

    
    func verifyCode(phoneNumber: String, secret: String) {
        
                self.user.auth = true
                
        }.task.resume()
        
    }
}

And then in my AuthView, I want to print the change when the function verifyCode is called:


 @EnvironmentObject var user: User

 var body: some View {
        
        print("AUTH SETTINGS -------->",user.auth)
        
        
        return VStack() { ........
            

CodePudding user response:

If your class User doesn´t contain any further logic it would be best to declare it as struct and either let it live inside your AuthViewModel or in the View as a @State var. You should have only one source of truth for your data.

As for the print question:

let _ = print(....)

should work.

  • Related