1

am working on a pagination using Firebase and so far i have a button to go forward and other one to get back and they are working fine ,but i have problem detecting either if am in the first page or the last page so i can disable the pagination buttons,so am wondering how that work and should i change the way i paginate data?

export const getNextItems = (last_Visible) => {
  return async (dispatch, getState, { getFirebase }) => {
    const firestore = getFirebase().firestore();
    // const items = [];
    const dbRef = firestore
      .collection('items')
      .orderBy('createdAt', 'desc')
      .startAfter(last_Visible)
      .limit(2);

   const usersRef = firestore.collection('users');
    let temps = [];

    const { data: items, firstVisible, lastVisible } = await dbRef.get().then(getAllDocs);
   

    for (const item of items) {
      const { data: user } = await usersRef.doc(item.owner).get().then(getDoc);
      temps.push({ ...item, owner: user });
    }

    return { docs: temps, lastVisible, firstVisible };
  };
};


export const getPrevItems = (first_Visible) => {
  return async (dispatch, getState, { getFirebase }) => {
    const firestore = getFirebase().firestore();
    // const items = [];
    const dbRef = firestore
      .collection('items')
      .orderBy('createdAt', 'desc')
      .endBefore(first_Visible)
      .limitToLast(2);
    const usersRef = firestore.collection('users');
    let temps = [];

    const { data: items, lastVisible, firstVisible } = await dbRef.get().then(getAllDocs);
    

    for (const item of items) {
      const { data: user } = await usersRef.doc(item.owner).get().then(getDoc);
      temps.push({ ...item, owner: user });
    }

    return { docs: temps, lastVisible, firstVisible };
  };
};

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
scripter
  • 1,211
  • 2
  • 11
  • 21
  • The only way to know if you're at the end is to ask for more documents than what you need, and see if you got less than that. – Doug Stevenson Jul 06 '20 at 01:07

1 Answers1

4

To detect whether there are more pages to load, you'll need to request an additional item. So since you seem to show 2 items per page, you should request 3 items - and display only two of them. If you get a third item, you know there's an additional page.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807