6

Is there a way to retrieve data from firebase with limit and offset? For example I have about 1000 elements in my firebaseRef and want to develop some kind of pagination. Is there a way I can do it without loading full list of objects.

For now I'm using queryLimitedToLast(limit) to do it and increase limit for every next page. But this method do not allow me to get pages count.

UPDATE:

One thing I did not mention but it's very important. My data showing from-last-to-first. Imagine it's a simple messenger but with pagination. So I want to show last 20 items, then 20 before these 20 etc.

Thanks.

anatoliy_v
  • 1,782
  • 15
  • 24
  • I answered your question about stepping through the pages below. Firebase does not have a built-in counter for the number of children. If you need that, you can implement it yourself. See this question: http://stackoverflow.com/questions/15148803/in-firebase-is-there-a-way-to-get-the-number-of-children-of-a-node-without-load – Frank van Puffelen Dec 29 '14 at 15:55

1 Answers1

10

Yup, paging through a long list of child nodes is definitely possible. The trick is to remember the key (or priority or whatever value you sort on) of the last item on the current page and then pass that into queryStartingAt... for the next page.

Kato wrote up a great example in his blog post on how to implement common SQL queries in Firebase:

// fetch page 2 of widgets
new Firebase("https://examples-sql-queries.firebaseio.com/widget")
   .startAt(null, lastWidgetOnPrevPage)
   .limitToFirst(LIMIT+1) // add one to limit to account for lastWidgetOnPrevPage
   .once('value', function(snap) {
      var vals = snap.val()||{};
      delete vals[lastWidgetOnPrevPage]; // delete the extraneous record
      console.log('widgets on this page', vals);
   });

This example is using the JavaScript SDK, but the relevant methods are also available in the iOS SDK.

Note that this snippet retrieves one extra item (LIMIT+1), since we start on the last item of the previous page.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you for a solution. I've updated my question. Forgot to mention one very important thing :) Any ideas how to implement it? – anatoliy_v Dec 29 '14 at 17:45
  • To start from the back, you can use `queryLimitedToLast and `queryEndingAt`. If you're using those, but it doesn't do what you expect it to do, you'll have to add a minimal reproduction of the problem to your question. Don't describe your code, show it. – Frank van Puffelen Dec 29 '14 at 17:52