Pr0tonion
Pr0tonion

Reputation: 207

SwiftUI closure update @State inside init

When I create a view I wish to login the user and when the login is complete, the view will change.

As I am quite new to SwiftUI it seems the way I am trying to this is not working. (I do know it has something to do with SwiftUI structs)

  1. I have a state variable to know if the progressView should animate
@State private var isLoading: Bool = true
  1. I have an escaping closure to login user
init() {
    userService.login { (didError, msg) in
    }
}
  1. Progress view(haven't tested it out yet)
ProgressView().disabled(isLoading).frame(alignment: .center)

When I try to do:

userService.login { (didError, msg) in
    isLoading.toggle() or self.isLoading.toggle()
}

Xcode return: Escaping closure captures mutating 'self' parameter.

Does anyone know how I can make something like this work?

Upvotes: 6

Views: 1276

Answers (1)

Asperi
Asperi

Reputation: 258305

Instead of init call it in .onAppear somewhere inside body, like

var body: some View {
   VStack {
      // .. some content
   }
   .onAppear {
      userService.login { (didError, msg) in
         self.isLoading.toggle()
      }
   }
}

Upvotes: 9

Related Questions