0/12
8. Cursor Pagination

Lesson 8: Cursor Pagination

When a stream has lots of data, you don't want to send it all at once. Cursor pagination lets clients load data page by page.

How it works

  1. The stream init function receives ctx as its first argument
  2. ctx.cursor is null on the first load, then the cursor you returned from the previous page
  3. Return { data, cursor, hasMore } instead of just the data
  4. The client calls store.loadMore() to fetch the next page

The fetch-one-extra trick

To know if there are more pages, fetch PAGE_SIZE + 1 items. If you get more than PAGE_SIZE back, there's another page. Return only PAGE_SIZE items to the client.

Try it

The starter code returns all 10 posts at once. Your task:

  1. Write a getPage(cursor) helper that slices the array from the cursor position, fetches PAGE_SIZE + 1 items, and returns { data, cursor, hasMore }
  2. Update the stream init to accept ctx and use getPage(ctx.cursor)
  3. Add a loadMore(cursor) RPC that calls getPage, publishes each item as a 'created' event, and returns the page info
  4. In the component, add a "Load more" button that calls loadMore with the current cursor and updates the hasMore state

Click "Load more" to see 3 more posts appear. Click again for the last batch. When all posts are loaded, the button disappears.

WebSocket
0
No messages yet
/