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
- The stream init function receives
ctxas its first argument ctx.cursorisnullon the first load, then the cursor you returned from the previous page- Return
{ data, cursor, hasMore }instead of just the data - 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:
- Write a
getPage(cursor)helper that slices the array from the cursor position, fetchesPAGE_SIZE + 1items, and returns{ data, cursor, hasMore } - Update the stream init to accept
ctxand usegetPage(ctx.cursor) - Add a
loadMore(cursor)RPC that callsgetPage, publishes each item as a'created'event, and returns the page info - In the component, add a "Load more" button that calls
loadMorewith the current cursor and updates thehasMorestate
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