I am trying to delete a list item from my ListStore but strangely it requires me to click the delete button twice. On the first click, the data is removed from Firebase, however the list item is then repopulated at the bottom of the list in UI. If clicked a second time the list item is then removed from the view. Fairly new to coding could use some help as to why it's not refreshing the view properly.
Class handling firebase data read
struct MyList : Identifiable, Equatable, Hashable {
var id = UUID()
var fid = String()
...
}
class ListStore : ObservableObject {
@Published var lists = [MyList]()
@Published var user: String = Auth.auth().currentUser!.uid
let db = Firestore.firestore()
init() {
readData()
}
func readData() {
db.collection("\(self.user)").addSnapshotListener {(snap, err) in
if err != nil {
print("Error: \(String(describing: err?.localizedDescription))")
return
} else {print("Data read successful")}
for i in snap!.documentChanges {
let documentId = i.document.documentID
DispatchQueue.main.async {
self.lists.append(MyList(fid: documentId))
}
}
}
}
}
Delete function in ListView.swift:
func delete(index: Int, id: String) {
db.collection("\(self.user)").document(id).delete(completion: { err in
if let err = err {
print("Error removing document: \(err)")
}
else {
print("Document \(id) successfully removed at index: \(index)")
}
self.listStore.lists.remove(at: index)
})
}
Button for removing list item that calls delete()
var scrollView: some View {
ScrollViewOffset {
scrollOffset = $0
} content: {
LazyVStack(spacing: 8) {
ForEach(Array(zip(listStore.lists.indices, listStore.lists)), id: \.0){index, l in
VStack (alignment: .center){
...
Button(action: {
self.delete(index: index, id: l.fid)
}) {
Image("trash")
}