Reputation: 15
I want to delete an item with its Id (let db = Firestore.firestore()
db.collection("Warenkorb").document(i.id).delete()
). So this is my code. Sadly when I'm deleting one item all items in the collection get deleted as well. Why? Can someone help me?
ForEach(cart.data) { i in
HStack{
Image("pic").resizable().scaledToFit().frame(width: 50, height: 75, alignment: .leading).padding().foregroundColor(.black)
Spacer()
VStack(alignment: .leading){
Text(i.name).font(.system(size: 25)).foregroundColor(.black)
HStack{
Text(i.preis).font(.system(size: 20)).foregroundColor(.black)
Text(i.size).font(.system(size: 20)).foregroundColor(.black)
}
}
Spacer()
Text("\(i.quantity)").font(.system(size: 25)).foregroundColor(.black)
Spacer()
if self.remove{
Button(action: {
let db = Firestore.firestore()
db.collection("Warenkorb").document(i.id).delete()
self.show.toggle()
self.show.toggle()
}) {
Image(systemName: "minus.circle.fill")
.resizable()
.frame(width: 20, height: 20)
.foregroundColor(.red)
}
}
Spacer()
}
.background(Color("Color-1")).frame(width: 350, height: 100).cornerRadius(30).padding(.leading)
}
Upvotes: 0
Views: 482
Reputation: 7254
You shouldn't add data access code in your SwiftUI views. Instead, implement a view model (and, optionally, a repository) to manage your data.
I've adapted your code a bit:
View
struct ShoppingCartView: View {
@ObservedObject var viewModel: ShoppingCartViewModel
var body: some View {
List {
ForEach(viewModel.lineItems) { lineItem in
VStack(alignment: .leading) {
Text(lineItem.title)
.font(.headline)
}
}
.onDelete { indexSet in
self.viewModel.deleteLineItems(at: indexSet)
}
}
}
}
View Model
import Foundation
import FirebaseFirestore
import FirebaseFirestoreSwift
import Combine
class ShoppingCartViewModel: ObservableObject {
@Published var lineItems = [LineItem]()
private var db = Firestore.firestore()
private var listenerRegistration: ListenerRegistration?
private var cancellables = Set<AnyCancellable>()
init() {
fetchData()
}
deinit {
unregister()
}
func unregister() {
if listenerRegistration != nil {
listenerRegistration?.remove()
}
}
func fetchData() {
unregister()
listenerRegistration = db.collection("shoppingCart").addSnapshotListener { (querySnapshot, error) in
guard let documents = querySnapshot?.documents else {
print("No documents")
return
}
self.lineItems = documents.compactMap { queryDocumentSnapshot -> LineItem? in
let lineItem = try? queryDocumentSnapshot.data(as: LineItem.self)
return lineItem
}
}
}
func deleteLineItems(at offsets: IndexSet) {
let itemsToDelete = offsets.lazy.map { self.lineItems[$0] }
itemsToDelete.forEach { lineItem in
if let id = lineItem.id {
db.collection("shoppingCart").document(id).delete()
}
}
}
}
Upvotes: 1