Scopique
Scopique

Reputation: 107

ReactJS + Firestore - Paging with document doesn't seem to work

I've been all over SE and the general web looking for insight but nothing has panned out so far.

Using React and Firestore, I'm trying to create a repository for my database access. Right now, I'm running tests so I have a few event handlers calling the methods in the repo to do very simple stuff. One of those methods is an attempt to get a list of user profile records in a Firestore collection called "profiles". Here's the repo method:

    getAllUsers = (sort, dir, perPage = 25, bookmark = null) =>
    {
        let query = this.db
            .collection("profiles")
            .orderBy(sort, dir)
            .limit(perPage)
        if (bookmark!== null){
            dir.toLowerCase() === "asc"
                ? query.startAfter(bookmark)
                : query.endBefore(bookmark)
        }
        return query.get();            
    }

And here's my test event from a test component:

const { firestore, firebase } = props;
const [ lastRecord, setLastRecord ] = useState(null);

    function GetAllUsers(){
        firestore.getAllUsers("displayName","asc", 2, lastRecord)
        .then((results)=>{
            results.forEach((doc)=>{
                const data = doc.data();
                console.log(data.displayName);
            });
            setLastRecord(results.docs[results.docs.length-1]);
        })
    }

My current dataset has 4 records, each with different displayName field values (there are other fields as well). Each run, even though the "last" document has been verified to be stored in lastRecord, returns the same 2 records based on the sort direction.

I've deconstructed the repo method several different ways, but haven't been able to get the "paging" to work, so I'm assuming that I'm misunderstanding at least ONE aspect of the process. Can anyone see what's wrong here? Thx.

Upvotes: 0

Views: 25

Answers (1)

LeadDreamer
LeadDreamer

Reputation: 3499

if (bookmark!== null){
            dir.toLowerCase() === "asc"
                ? query.startAfter(bookmark)
                : query.endBefore(bookmark)

Does not modify query in any way. query.startAfter(bookmark) creates and returns a NEW query, but you don't save it anywhere. Perhaps you meant:

query = bookmark!== null
        ? dir.toLowerCase() === "asc"
          ? query.startAfter(bookmark)
          : query.endBefore(bookmark)
        : query;

Upvotes: 1

Related Questions