LazyVGrid(columns: items, spacing: 2, content: { ForEach(searchingText.isEmpty ? [] : viewModel.filteredPosts(searchingText)) { post in NavigationLink( destination: Postview(viewModel2: PostViewModel(post: post)) .onAppear{ currentListener = Firestore.firestore().collection("posts").document(post.postId).addSnapshotListener { snapshot, err in guard let index = self.viewModel.filteredPosts(searchingText).firstIndex(where: { $0.id == post.id }) else { return } if let doc = try? snapshot?.data(as: Post.self) { self.viewModel.filteredPosts(searchingText)[index].liked = doc.liked } } } ,label: { Text("See likes") }) } })
func filteredPosts(_ query: String) -> [Post] { let lowercasedQuery2 = query.lowercased() return posts.filter({ $0.caption.lowercased().contains(lowercasedQuery2) }) }
I am getting :
"Cannot assign to property: function call returns immutable value" error in this part: "self.vm2.filteredPosts(searchingText2)[index].liked = doc.liked".
Any idea how I can solve it? My goal is to add a snapshot listener when a user clicks on a post after searching but I haven't been able to make it work.