Firebase pagination not working when fetching posts from different users

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Firebase pagination not working when fetching posts from different users



I am trying to paginate data from firebase with a query based on "creationDate" and my code works when I am not following anyone, but as soon as I follow someone with a different uid, the main feed begins to duplicate posts and not order them correctly. Here's what a snapshot of the data I am fetching looks like:



enter image description here



The snapshot key is the key of the post that is later fetched and the child of this snapshot holds references to the poster's UID, as well as the creationDate of the post, which is used to order the query. The code for fetching the data is below:


static func loadPosts(posts: [Postt], isFinishedPaging: Bool, completion: @escaping ([Postt], Bool) -> Void) {
guard let uid = Auth.auth().currentUser?.uid else {return}
var pagingTemp = isFinishedPaging
let ref = Database.database().reference().child("feed").child(uid)
var query = ref.queryLimited(toLast: 4).queryOrdered(byChild: "creationDate")
if posts.count > 0 {
let value = posts.last?.creationDate.timeIntervalSince1970
query = query.queryEnding(atValue: value)
}
query.observeSingleEvent(of: .value, with: { (snapshot) in
var completedPosts = [Postt]()
guard var allObjects = snapshot.children.allObjects as? [DataSnapshot] else {return}

allObjects.reverse()
if allObjects.count == 0 || allObjects.count == 1 {
pagingTemp = true
}
if posts.count > 0 && allObjects.count > 0 {
allObjects.removeFirst()
}
let dispatchGroup = DispatchGroup()

for postData in allObjects {
guard let postDict = postData.value as? [String : Any],
let postId = postDict["post_uid"] as? String
else { return }
dispatchGroup.enter()

PostClient.show(forKey: postData.key, uid: postId) { (post) in
if let post = post {
completedPosts.append(post)
}
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main, execute: {
completion(completedPosts, pagingTemp)
})
}) { (err) in
print("Failed to fetch posts: ", err)
}
}









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Arduino Mega cannot recieve any sketches, stk500_recv() programmer is not responding

Visual Studio Code: How to configure includePath for better IntelliSense results

Future solutions