0

So, i'm creating a simple login page where an async call is made passing the credentials and with a successful response, it should navigate to another view. The call is working just fine, i've managed to receive the correct response, but i can't get the navigationDestination(isPresented:destination:) to work. Any clues on what i'm missing here?

LoginView:

struct LoginView: View {
    @StateObject private var loginViewModel = LoginViewModel()
    @State var success: Bool = false
    
    var body: some View {
        VStack {
            if loginViewModel.isBusy {
                ProgressView()
            } else {
                NavigationStack {
                    TextField("Username", text: $loginViewModel.username)
                    SecureField("Password", text: $loginViewModel.password)
                    Button("Login") {
                        Task {
                            success = await loginViewModel.login()
                        }
                    }
                    .navigationDestination(isPresented: $success) {
                        HomeView()
                    }
                }
                .buttonStyle(PlainButtonStyle())
            }
        }
    }
}

LoginViewModel:

@MainActor
class LoginViewModel: ObservableObject {
    @Published var response: LoginResponse?
    @Published var isBusy: Bool = false
    var username = ""
    var password = ""
    
    func login() async -> Bool {
        isBusy = true
        do {
            response = try await Service().login(username: username, password: password)
            isBusy = false
            return true
        } catch {
            isBusy = false
            print(error.localizedDescription)
            return false
        }
    }
}
Boga
  • 371
  • 3
  • 14
  • Try adding another Published variable in your viewModel that you update with your login function. As an example: Published var isLoggedIn = false, and then in your view add .onChange(of: loginViewModel.isLoggedIn) { isLoggedIn in if isLoggedIn { success = true } } – bjorn.lau Oct 29 '22 at 23:50

0 Answers0