Home > Mobile >  EnviromentObject trigger closes child view presented with NavigationLink
EnviromentObject trigger closes child view presented with NavigationLink

Time:11-26

I got an EnvironmentObject that keeps track of the current user with a snapshotlistener connected to Firestore.

When the database get updated it triggers the EnvironmentObject as intended, but when in a child view presented with a NavigationLink the update dismisses the view, in this case PostView get dismiss when likePost() is called.

Should't the view be updated in the background?

Why is this happening, and what is the best way to avoid this?

class CurrentUser: ObservableObject {
   @Published var user: User? 

   init() {
      loadUser()
   }

   func loadUser() {
      // firebase addSnapshotListener that sets the user property
   }
}

MainView

struct MainView: View {
   @StateObject var currentUser = CurrentUser()

   var body some view {
      TabView {
         PostsView()
            .enviromentObject(currentUser)
            .tabItem {
               Label("Posts", systemImage: "square.grid.2x2.fill")
            }
      }
   }
}

Shows All Posts

struct PostsView: View {
   @ObservableObject var viewModel = PostsViewModel()
   @EnviromentObject var currentUser: CurrentUser

   var body some view {
      NavigationLink(destination: PostView()) {
         HStack { 
            // Navigate to post item 
         }
      }
   }
}

Show Posts Detail

When im on this View and likes a post it's added to the document in Firestore, and triggers the snapshot listener. This causes the the PostView to be dismiss which is not what I want

struct PostView: View {
   @ObservableObject var viewModel: PostViewModel

   var body some view {
      PostItem()
      Button("Like Post") {
         likePost()
         // Saves the post into the current users "likedPosts" document field in Firestore
         // This trigger the snapshotListener in currentUser and
      }
   }
}

CodePudding user response:

It seems that PostsView is replaced, try to use StateObject in it, like

struct PostsView: View {
   @StateObject var viewModel = PostsViewModel()    // << here !!

...
  • Related