如何解决从 swiftUI 更改 Firestore 收集路径
我从 Firestore 集合中提取了一个数组并显示在 swiftUI 列表中。但是,如果用户选择使用按钮查看它们,我想从不同的集合中提取文档。例如:
按钮 1 → 也收听并从 collectionA 加载
按钮 2 → 也收听并从 collectionB 加载
我想在本地加载和传递集合名称,但是当我这样做时,列表不会更新;它只是显示没有数据。 (现在,我在 Firestore 上更新了一个变量,如下所示,并监听更新以更改收集路径,这并不理想……但确实有效)
几秒钟后,我可以用用户的新集合选择打印出新数组,但列表视图没有填充数据。
这是一些相关的代码:
struct PostStruct: Identifiable,Codable {
@DocumentID var id: String?
var Title: String
var Content: String
}
@Published var arrayToPopulateList: [PostStruct] = []
func getDataForList() {
if uniqueUserUID != "" {
//this is the only work around I found → pulling the selected collection from firestore is the only way I can get the swiftUI list to update when the user picks a new collection to view
store.collection(uniqueUserUID).document("selection")
.addSnapshotListener { (querySnap,error) in
if let selection = querySnap?.data()?["selected"] {
//accesses the collection with path that user picks (ex from buttons that yield different content)
self.store.collection(selection as! String)
.addSnapshotListener { querySnapshot,error in
if let error = error {
print("Error getting postArray: \(error.localizedDescription)")
return
}
self.arrayToPopulateList = querySnapshot?.documents.compactMap { document in
try? document.data(as: PostStruct.self)
} ?? []
}
}
}
}
}
为了显示加载的数组,我在 swiftUI 中使用了一个列表。
有什么想法吗?谢谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。