如何从 SwiftUI 中的列表中删除 Firestore 文档

How do I delete a Firestore Document from a List in SwiftUI

这是我的视图模型

import FirebaseFirestore
import FirebaseFirestoreSwift

struct Todo: Codable, Identifiable, Hashable {
    @DocumentID var id: String?
    var todoDetais: String?
}

这就是我显示列表的方式,忽略“详细信息”中的拼写错误。

var body: some View {
    NavigationView {
        List {
            ForEach(viewModel.todos, id: \.self) { todo in
                VStack{
                    Text(todo.todoDetais!)
                }
            }
            .onDelete(perform: delete)
        }

我的获取数据和映射。

    func fetchData() {
    db.collection("todos").addSnapshotListener { (querySnapshot, error) in
        guard let documents = querySnapshot?.documents else {
            print("No documents")
            return
        }
        
        self.todos = documents.map { (QueryDocumentSnapshot)  -> Todo in
            let data = QueryDocumentSnapshot.data()
            let todoDetails = data["todo"] as? String ?? ""
            
            return Todo(todoDetais: todoDetails)
        }
    }
}

删除逻辑,我可以从列表中删除,但如何从 Firestore 中删除?

    func delete(at offsets: IndexSet) {
    viewModel.todos.remove(atOffsets: offsets)
    
    //I need to delete a firestore document at the index im removing at?
    
}

您可以通过执行以下操作将偏移量映射到您的 Todo 模型:

offsets.map { viewModel.todos[[=10=]] }

因此,您的删除函数可能如下所示:

func delete(at offsets: IndexSet) {
  offsets.map { viewModel.todos[[=11=]] }.forEach { todo in 
    guard let todoID = todo.id else { return }
    db.collection("todos").document(todoID).delete() { err in
      if let err = err {
        print("Error removing document: \(err)")
      } else {
        print("Document successfully removed!")
      }
    }
  }
}

如果你有一堆,你可以考虑批处理请求,但这应该让你开始。