NamanD
NamanD

Reputation: 669

Returning interfered by get documents firestore swift

I've been trying to get paginated data, but for some reason, I'm not able to get this right. I did the debugging quite a few times, but with the absence of any errors it seems this is the expected behavior from Firestore getDocuments. Any help would be appreciated -> I am trying to return the posts variable from the method below

private var query: Query
    private var documents: [QueryDocumentSnapshot] = []

    init() {
        let db = Firestore.firestore()
        self.query = db.collection("posts").order(by: "createdTimeStamp")
    }

    func updateQuery() -> Query{
        let nextQuery: Query
        if let lastDocument = documents.last {
            nextQuery = query.start(afterDocument: lastDocument).limit(to: 5)
        } else {
            nextQuery = query.limit(to: 5)
        }
        return nextQuery
    }

    public func fetchNext() -> [ObjectPost] {
        var posts: [ObjectPost] = []
        let updatedQuery = updateQuery()

        updatedQuery.getDocuments(completion: { (querySnapshot, error) in
            if let e = error {
                print(e.localizedDescription)
            }

            guard let snapshot = querySnapshot else {
                print("Error fetching next documents: \(error!)")
                return
            }

            let newPosts = snapshot.documents.map { doc -> ObjectPost in
                let post = try! FirestoreDecoder().decode(ObjectPost.self, from: doc.data())
                print("post \(post.postBody)")
                return post
            }

            posts += newPosts
            print("--After posts update")
            self.documents += snapshot.documents
            print("--After documents update")
        })

        print("Before returning posts")
        return posts
    }

I am able to reach till "After documents update" but it never reaches "Before returning posts" and also the posts are never returned. What am I missing here?

UPDATE: For those reading this as a means to solve their own queries, I was missing the asynchronous nature of the Firebase APIs, which is very well explained here https://medium.com/firebase-developers/why-are-firebase-apis-asynchronous-callbacks-promises-tasks-e037a6654a93 and here https://firebase.googleblog.com/2018/07/swift-closures-and-firebase-handling.html

Upvotes: 0

Views: 337

Answers (1)

Paul Beusterien
Paul Beusterien

Reputation: 29582

You're missing that the return statement is in the closure that runs asynchronously after the return from the fetchNext function.

See the Firestore quickstart for some examples of managing data in a closure completion block.

Upvotes: 1

Related Questions