Todos with a live query
A todo list built on one db collection. Add, check off and delete todos: each change shows at once, while the fake server takes almost a second to answer. Turn on Make writes fail and every change is reverted when the error arrives, without any rollback code.
Loading the example...
Run locally
npx tiged BetterTyped/hyper-fetch/examples/db/todos hyper-fetch-db-todos && cd hyper-fetch-db-todos && npm install && npm run devWhat it shows
- A collection made from the requests you already have:
loadreads the rows,mutatesaves the changes. useLiveQueryrenders the rows and re-renders on every change, with no cache keys and no dependency array.- Local filters: the loader sends no filters, so the All, Active and Done tabs filter the loaded rows without a request.
- Optimistic writes:
db.todo.insert(),update()anddelete()change every query at once and revert on failure. - No backend needed:
server.tsanswers the requests withsetMock, so the db sends exactly what it would send to a real API.
How it works
db.tsdefinesTodoSchemawith Zod. The schema is the row type, and a loader or write that returns other rows does not compile.collection(TodoSchema, { key: "id" }).load(getTodos)saysGET /todosreturns complete rows. The loader declares nowhere, so every query is served from that one list..mutate()maps each write to its request.updategets the key and the changed fields, somapbuilds the params and the payload ofPATCH /todos/:todoId.App.tsxbuilds a query for the current tab,db.todo.orderBy(...)with aneq(todo.completed, ...)filter, and passes it touseLiveQuery. A second query counts the todos left. Both update together after every write.- A write resolves with
{ success }and never throws. When the request fails, the db has already removed the change from every query, and the log shows it.
When to use it
- Any list that the user edits in place: todos, settings, labels, tags.
- Screens where one change shows in several places, like a list and a counter.
Related
Summary
You turned three requests into a collection, read it with one live query and wrote to it with optimistic writes that revert on their own.