Search code examples
swiftswiftuiview

Get object at the start of view swiftui


I have a view and I want to load the data from the database from the start of the view, because I want to edit the profile of my user.
So whenever I will start the my view, the data will be loaded. This is my code but it gives me an exception on the TextField.

struct ProfileView: View {
    @State var  myUser = User()
    var repo = myRepo()

     var body: some View {
        VStack{
            Form{
                Section(header: Text("edit the name")){
                    TextField("Nume produs", text: self.myUser.name) //IT DOES NOT WORK HERE
                }
            }
        }.onAppear(){
            getMyUser()    
        }

    func getMyUser(){
        Task{
            do{
                try await repo.getUserProfile().watch(block: {item in
                    self.myUser = item as! User
                })
            }catch{
                print("error")
            }
        }
    }
}

This just does not work when I put as a TextField What is the best way to have the data of my object (myUser) right away on the start of the view?


Solution

  • Just init the String as empty and create the @Binding like so:

    import SwiftUI
    
        struct ProfileView: View {
            @State var  myUser = ""
            
            var body: some View {
                VStack{
                    Form{
                        Section(header: Text("edit the name")){
                            TextField("Nume produs", text: $myUser) //IT DOES NOT WORK HERE
                        }
                    }
                }.onAppear(){
                    getMyUser()
                }
            }
            
            func getMyUser() {
                Task{
                    do{
                        try await Task.sleep(nanoseconds: 3_000_000_000)
                        
                        myUser = "HELLO"
                    }catch{
                        print("error")
                    }
                }
            }
        }
    

    enter image description here