How to populate TextFields with data from network calls in SwiftUI?

Viewed 222

I get User Profile information from a API call and want to populate the existing data (like name, gender etc) into my user profile field. However, I have no idea how to assign the state variables (fullName) of TextFields. The following code is a sub view of the full form view. I make the network call on the parent view .onAppear{}. Here is my Code:

import SwiftUI

struct FormPartOneView: View {
    @State var fullName: String = ""

    @ObservedObject var userProfile = UserProfileViewModel()

    var body: some View {
        GeometryReader { geometry in
            VStack {
                TextField("Full Name", text: self.$fullName)
                    .padding(.horizontal)
            }
            .font(.system(size: 13))
            .frame(width: geometry.size.width/1.2, height: 40)
            .overlay(
                RoundedRectangle(cornerRadius: 5)
                    .stroke(Color("Border2"), lineWidth: 1)
            )
            .onAppear {
                self.userProfile.fetchWithAF()
            }
        }
    }
}

struct FormPartOneView_Previews: PreviewProvider {
    static var previews: some View {
        FormPartOneView()
    }
}

This below code contains Full Name from decoded json data:

self.userProfile.userProfileModel?.payload[0].fullName ?? ""

So I would like to know how can I populate the Full name into the full name TextField in the form.

Here is the form view:

User Profile Update Form

1 Answers

If I correctly understood your model you can set it in .onReceive modifier, like

.onAppear {
    self.userProfile.fetchWithAF()
}
.onReceive(self.userProfile.$userProfileModel) { model in
    self.fullName = model?.payload[0].fullName ?? ""
}
Related