A team feed that stays live
A team feed on one db collection. The posts of a team load once, then three socket events keep them current. Use Simulate another user to create, rename and delete a post on the fake server: the list changes at once, with no refetch. Open the page in a second tab, and a like or a simulated post in one tab shows in the other.
Loading the example...
Run locally
npx tiged BetterTyped/hyper-fetch/examples/db/realtime-feed hyper-fetch-db-realtime-feed && cd hyper-fetch-db-realtime-feed && npm install && npm run devWhat it shows
- A loader with a required filter:
where: { teamId: { eq, required: true } }loads one team's posts, so a query must name the team. - Three syncs:
insert,updateanddeletelisteners add, change and remove rows in every query, with no refetch. - Scoped topics: each sync maps the query's
teamIdto the listener's:teamIdparam, so a team only receives its own events. The Syncs for this query panel shows the topics. - Optimistic likes:
db.post.update()shows the new count at once and reverts it when the server fails. stale: disconnect the socket and the badge changes. Reconnect and the db refetches the feed, since it may have missed events.- No backend needed: requests use
setMock, and the socket runs over aBroadcastChannel, so it works in the browser alone and across tabs.
How it works
db.tscreates the client, a socket and three listeners:teams/:teamId/posts/created,/changedand/deleted. In a real app the socket uses a WebSocket URL and the default adapter. Nothing else changes.collection(PostSchema, { key: "id", version: "updatedAt" })loads posts withgetTeamPostsand declares one.sync()per listener.byTeammaps theteamIdfilter to the listener param.App.tsxbuildsdb.post.where((post) => eq(post.teamId, teamId))for the selected team and reads it withuseLiveQuery. Switching teams is a different query. The first team's rows stay in the db for a while, so switching back shows them at once.server.tskeeps the posts inlocalStorageand publishes each change on aBroadcastChannelwith the same name as the socket URL. The topic is the listener topic with its params filled in, such asteams/design/posts/created.- A like is an optimistic
update. The server saves it and publishes achangedevent, so other tabs get the new count. With Make writes fail on, the request fails and the db puts the old count back. - While its syncs are live the feed is fresh. When the socket drops, the feed reports
staleright away, and the reconnect refetches it.
When to use it
- Feeds, chats, dashboards and boards that several people change at once.
- Any list a server pushes changes for, scoped per team, project or room.
- Screens that should show when they may be out of date, with a badge instead of a spinner.
Related
Summary
You loaded one team's posts with a REST loader, kept them live with insert, update and delete syncs scoped to the team,
liked posts with optimistic writes, and showed when the feed may be out of date with stale.