Swift UI navigation Stack - infinite loop

161 views Asked by At

I am loading a page inside NavigationStack as given below,

@State private var showLoginView = false
var body: some View {
    

NavigationStack {
        content()
            .navigationDestination(isPresented: $showLoginView) {
            LoginView(viewModel: LoginViewModel(pageId: "login_view"))
        }.navigationDestination(isPresented: $showRegistrationView) {
            RegistrationView(viewModel: RegistrationViewModel(pageId: "registration_view"))
        }.navigationDestination(isPresented: $continueAsGuest, destination: {
            TabbedView(viewModel: TabbedViewModel())
        })
    }
}

On a button click, I set the value of showLoginView as true and load the login view. The login view has options to login and has two buttons, one for forgot password and the other to register a new account.

var body: some View {
            content()
                .navigationDestination(isPresented: $showForgotPasswordView, destination: {
                    ForgotPasswordView(viewModel: ForgotPasswordViewModel(pageId: "forgot_password_view"))
                })
                .navigationDestination(isPresented: $showRegistrationView, destination: {
                    RegistrationView(viewModel: RegistrationViewModel(pageId: "registration_view"))
                })
    }

I am setting showRegistrationView as true on button click, and the value is set to true only once, but the ForgotPasswordView or RegistrationView is called infinite times and it never ends. What's the reason for this behavior?

To prevent this, I am setting the value to false like this,

ForgotPasswordView(viewModel: ForgotPasswordViewModel(pageId: "forgot_password_view")).onAppear {
                        self.showForgotPasswordView = false
                    }

This prevents infinite loading and loads the view correctly, but when I dismiss the view, the LoginView is displayed for a second and immediately an empty view is loaded, but if I click back on that empty view the initial view is displayed.

I am not sure why the destination is triggered infinite times and also when dismissed why an empty view is displayed.

0

There are 0 answers