Search code examples
swiftuiswiftui-navigationlinkswiftui-navigationview

Can a NavigationLink perform an async function when navigating to another view?


I'm trying to create a navigation link in SwiftUI that logs in a user and navigates to the next screen.

I've tried using .simultaneousGesture as shown below, based on this solution. When I have it perform a simple action (e.g. print("hello")), the code works fine and navigates to the next page, but when I have it perform my authState.signUp function (which is async), it calls the function but doesn't navigate to the next page.

Is there a different way I should be approaching this?

NavigationLink(destination: NextView()) {
    Text("Create account")
}
.simultaneousGesture(TapGesture().onEnded {
    authState.signUp(user: user)
})

Solution

  • you can use a selection arg of navigationLink

    add this var

    @State var trigger: Bool? = nil
    

    and use

    NavigationLink(destination: NextView(), tag: true,
                                       selection: $trigger ) {
    }
    

    when ever your other job (login) is done toggle() the trigger and navigationLink fires.