简体   繁体   English

更新文档时无限循环 Firebase

[英]Infinity Loop while updating a document Firebase

I try to update a document in my Cloud Firestore, the function is working nicely on the first tap of the lifecycle of the app, but on the second, the function start and goes into an infinity loop.我尝试更新我的 Cloud Firestore 中的文档,function 在应用程序生命周期的第一次点击中运行良好,但在第二次点击中,function 启动并进入无限循环。

I tried .update([Data]) and .set([Data]) they both works on first tap, and goes infinite on the second我试过.update([Data]).set([Data])他们都在第一次点击时工作,第二次进入无限

func modifyInfoOwner(info: UserInfo){
    let fireStoreDB = Firestore.firestore()
    var documentID = ""
    fireStoreDB.collection("Users").whereField("email", isEqualTo: info.email).addSnapshotListener(includeMetadataChanges: false) { (snapshot, error) in
        if error != nil {
            print(error?.localizedDescription)
        } else {
            if snapshot?.isEmpty != true && snapshot != nil {
                for document in snapshot!.documents {
                    print("| saving info in DB")
                    print("v")
                    print(info)
                    documentID = document.documentID
                    //                        fireStoreDB.collection("Users").document(documentID)
                    fireStoreDB.collection("Users").document(documentID).setData(["adress" : info.adress, "name" : info.name, "phone" : info.phoneNumber, "seatQuantity" : info.seatQuantity, "email" : info.email, "token" : info.token]){ error in
                        if let error = error {
                            print("Data could not be saved: \(error).")
                        } else {
                            print("Data saved successfully!")
                        }
                    }
                }
            }
        }
    }
}

} }

You're updating the same document that you're querying for.您正在更新您正在查询的同一个文档。 And since you use addSnapshotListener , the listener stays active after it first gets the data.而且由于您使用addSnapshotListener ,因此侦听器在首次获取数据后保持活动状态。 So when you call setData on a document, your listener gets triggered again, which causes it to setData again, and that's your endless loop.因此,当您在文档上调用setData时,您的侦听器会再次被触发,这会导致它再次setData ,这就是您的无限循环。

The solution here is to use getDocuments instead of addSnapshotListener .这里的解决方案是使用getDocuments而不是addSnapshotListener With getDocuments , you read the data only once, so the update won't trigger it again.使用getDocuments ,您只读取一次数据,因此更新不会再次触发它。

fireStoreDB.collection("Users")
  .whereField("email", isEqualTo: info.email)
  .getDocuments(includeMetadataChanges: false) { (snapshot, error) in
      ...

The rest of your code won't have to change.您的代码的 rest 不必更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM