Skip to content
Advertisement

How can I make Infinite Scroll using Firebase Realtime Database – v9

DB Structure

I want to make a Infinite scroll to load only 2 users data at first, then when admin will click on Load More button, it should load next 2 user data. Is it possible in Realtime Database? Similarly, I can use this to display users their post to limited numbers if they have many posts in the database instead to loading all the posts at once.

I tried it by using orderByChild() method, but it doesn’t work as expected. I am beginner in Firebase.

Edit: Thank you Jay for guiding me. Here is json database structure:

{
  "users": {
    "BZh9dyH3fMTqoKFIOb38Px0ha243": {
      "info": {
        "private": {
          "displayName": "John",
          "email": "john@gmail.com",
          "emailVerified": true,
          "isAnonymous": false,
          "metadata": {
            "createdAt": 1661687731596,
            "lastLoginAt": 1669986823839
          },
          "photoURL": "https://...profile.png"
        },
        "public": {
          "displayName": "John",
          "photoURL": "https://...profile.png"
        }
      }
    },
    "RpxBOI7jXHef5NyEFFaI29ZMXcw2": {
      "info": {
        "private": {
          "displayName": "Albert",
          "email": "albert@gmail.com",
          "emailVerified": true,
          "isAnonymous": false,
          "metadata": {
            "createdAt": 166168790988,
            "lastLoginAt": 1669986823839
          },
          "photoURL": "https://...profile.png"
        },
        "public": {
          "displayName": "Albert",
          "photoURL": "https://...profile.png"
        }
      }
      // more users...
    }
  }
}

Code I have tried:

let last = 0;
let getNextData = () => {
  let dataRef = last === 0 ? query(ref(db, 'users'), orderByChild("info/private/metadata/createdAt"), limitToFirst(2)) : query(ref(db, 'users'), orderByChild("info/private/metadata/createdAt"), limitToFirst(2), startAfter(last));
    
  get(dataRef).then((snapshot) => {
    last += snapshot.size
  })
}
// load first two users
getNextData()
// load more
gId("loadMore").addEventListener("click", () => getNextData())

But it loads only 2 users every time.

Advertisement

Answer

Yes, it is possible to load limited data from the Realtime Database using the limitToFirst() or limitToLast() methods in combination with the orderByChild() method.

For example, if you want to load the first 2 users in your database, you can use the following query:

const query = database.ref('users').orderByChild('timestamp').limitToFirst(2);

Then, when the admin clicks on the “Load More” button, you can load the next 2 users using the following query:

const query = database.ref('users')
    .orderByChild('timestamp')
    .startAt(lastLoadedTimestamp)
    .limitToFirst(2);

Where lastLoadedTimestamp is the timestamp of the last user that was loaded previously.

This way, you can paginate the data and load it in small chunks instead of loading all of it at once. You can find more information about paginating data in the Realtime Database in the Firebase documentation: https://firebase.google.com/docs/database/web/lists-of-data#paginate_data

Edit:

To get the timestamp of the last time data was saved to a snapshot in Firebase, you can use the .getMetadata() method on the snapshot object. This method returns an object containing metadata about the snapshot, including the timestamp. Here is an example:

var ref = firebase.database().ref("my_data");
ref.on("value", function(snapshot) {
  // Get the timestamp of the last time the data was saved
  var timestamp = snapshot.getMetadata().timestamp;
});

Note that this method will only return a timestamp if the snapshot was saved with a server-side timestamp. If the snapshot was saved with a client-side timestamp, this method will not return a value. Additionally, this method will only work if you are using the Realtime Database in Firebase. If you are using Cloud Firestore, you will need to use a different approach to get the timestamp.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement