Home > Software design >  NavigationLink redirecting me to previous view after appending data to Firebase Realtime Database
NavigationLink redirecting me to previous view after appending data to Firebase Realtime Database

Time:07-16

I am using SwiftUI and Firebase Realtime Database within my project and whenever I try changing the contents of my database, and then redirect the user to the next view, the view changes briefly and then get redirected back.

Here is a simplified version of my code to help you understand:

import SwiftUI
import Firebase
import FirebaseDatabase

struct someView: View {
    
    private var randomText = ["hello", "world"]

    @State private var showNextView = false

    var ref: DatabaseReference!

    init() {
        ref = Database.database!.reference()
    }

    var body: some View {

        ZStack {
            NavigationLink("", destination: nextView(), isActive: $showNextView)
            Button {
                save()
                self.showNextView.toggle()
            } label : {Text("Save")}
        }
    }

    func save() {
        self.ref.child("users/\(Auth.auth().currentUser!.uid)/someName").setValue(randomText)
    }

}

struct nextView: View {
    
    var body: some View {
        ZStack {
            Text("This is the next view")
        }
    }
}

When I click the button within someView, the array is saved correctly in the database. I then get redirected to nextView where I see the text "This is the next view" - as expected. However, this only shows briefly and then the view jumps back to someView again. I am unsure why this is and cannot find any information as to how to fix it.

CodePudding user response:

I assume this happens because click handled and by Button and by NavigationLink which right under button, so try to hide link completely to make it activate only programmatically, like

    ZStack {
        NavigationLink(destination: nextView(), isActive: $showNextView) { 
            EmptyView()    // << here !!
        }.disabled(true)   // << here !!

        Button {
            save()
            self.showNextView.toggle()
        } label : {Text("Save")}
    }

CodePudding user response:

You need to wrap your ZStack inside a NavigationView if you want to use NavigationLink.

NavigationView {
   ZStack {
        NavigationLink("", destination: nextView(), isActive: $showNextView)
        Button {
            save()
            self.showNextView.toggle()
        } label : {Text("Save")}
    }
}
  • Related