An infinite feed that stays live
A feed of 60 posts that loads page by page. Scroll down or press Load more, and the server log shows each request. Press Publish a post as another user: the post arrives over the socket and lands at the top, and every loaded page stays on screen. Likes show at once and revert when the server fails.
Loading the example...
Run locally
npx tiged BetterTyped/hyper-fetch/examples/db/infinite-feed hyper-fetch-db-infinite-feed && cd hyper-fetch-db-infinite-feed && npm install && npm run devWhat it shows
- A cursor loader:
cursorreads the next page's cursor from a response, andpagesends it with the next request. useLiveInfiniteQueryshows the ordered query as pages of 10, withpages,hasNextPageandfetchNextPage.- UI pages are not backend pages: the server sends 15 posts per request. Page 2 shows 5 posts at once, and the loader fetches the rest.
- Scroll to load: an
IntersectionObserveron an element after the list callsfetchNextPage(). - Live pages: an
insertsync adds new posts at the top and pushes the last row to the next page, with no refetch. Anupdatesync keeps likes in step across tabs. - Optimistic likes:
db.post.update()changes the count at once and reverts it when the server fails.
How it works
db.tsdeclaresgetPosts, which answers{ items, next }. The loader reads rows withrows, the next cursor withcursor, and sends it withpage.- A paginated loader must send every order a query uses, so
orderBysays how the endpoint sorts bycreatedAt. A query that sorts by another field does not compile. App.tsxpassesdb.post.orderBy((post) => post.createdAt, "desc")touseLiveInfiniteQuerywith{ pageSize: 10 }. The query must haveorderBy, so a page never shifts between renders.fetchNextPage()widens the window by one page. Rows the db holds show at once. When the window runs past them, the loader requests the next backend page. A second call while a page loads does nothing, so a double scroll event is harmless.server.tspublishesposts/createdfor a post by another user. The new post sorts before the last loaded row, so it joins the first page and the loaded pages shift by one.- Open the page in a second tab: the posts live in
localStorageand the socket runs over aBroadcastChannel, so a post or a like in one tab shows in the other.
When to use it
- Social feeds, activity streams, comment threads and inboxes that receive new items while you scroll.
- Long lists where items also change from sockets or writes, and refetching every page would be too slow.
- Lists that load from a cursor or limit endpoint but should show pages of your own size.
Related
Summary
You paginated a feed with a cursor loader, showed it in pages of your own size with useLiveInfiniteQuery, loaded more
on scroll, and kept every loaded page live with socket syncs.