In this episode, we're diving into cursor pagination and sorting out some quirks with our post ordering and pagination UI.
We start by fixing the order of our records. Because we initially used a factory to generate posts with nearly identical "created_at" timestamps, things looked weirdly ordered. So, we pare down our records to 15 and manually adjust their timestamps so they appear in true sequential order. This makes it much clearer how pagination moves through the records.
After that, we post some new items and see how the default pagination can actually get a bit out of sync if you add records while paging, which leads us neatly into introducing cursor pagination. We swap out our usual paginate
method for cursorPaginate
, and discuss some immediate differences. Cursor pagination doesn't give you as much info (like total pages or last page URLs), but for infinite scroll/load-more-type interfaces, just having the next page URL is all you really need.
We test out how it works in the UI—showing that it keeps the order intact, even when adding new records—and notice a bug where the "Load more" button keeps firing requests even when there are no more posts. To fix that, we simply add a quick check: only show the button if next_page_url
isn't null. That cleans up the UI and makes everything work nice and smooth.
By the end of this episode, you'll have a much better understanding of cursor pagination and why/when it's a great choice, especially if you want more consistent loading of content as your data changes.