Skip to content
Source
Sign inSign up
fuko/trytanstackdb-v2
Open History to see the last commit

content.tsx

440 lines18.6 KB

1/**
2 * The guide: one section per idea, each with something to do in the app.
3 * Section ids are stable: the app's state maps to them (`appStates`, see
4 * `lib/app-state.ts`), and the dev menu, the mobile header chip and section
5 * progress refer to them.
6 *
7 * Code snippets come from `snippets.ts`, which quotes the app's own source.
8 * Copy has to work in both layouts: the app beside the guide (wide screens)
9 * and the app in a sheet opened with "Try it" (phones). Where it can't, use
10 * `ByGuideLayout`.
11 */
12import { Link, linkOptions } from "@tanstack/react-router";
13import type { LinkOptions } from "@tanstack/react-router";
14import type { ReactNode } from "react";
15​
16import { Callout } from "@/components/guide/callout";
17import { LiveWordsChart } from "@/components/guide/live-words-chart";
18import { ShowMe } from "@/components/guide/show-me";
19import { SourceSnippet } from "@/components/guide/source-snippet";
20import { ByGuideLayout } from "@/components/guide/try-it";
21import { NOTE_TITLE_MAX_LENGTH } from "@/api/fake-server";
22import type { AppActionMatcher } from "@/lib/app-actions";
23import type { AppState } from "@/lib/app-state";
24​
25import { SNIPPETS } from "./snippets";
26​
27export interface GuideSectionContent {
28 id: string;
29 eyebrow: string;
30 title: string;
31 /** Label for the active-section chip in the mobile header. Keep it short: it's never truncated. */
32 shortTitle: string;
33 /**
34 * The app states this section explains: the section lights up when the
35 * app is in one of them. Empty when no app state matches it.
36 */
37 appStates: AppState[];
38 /**
39 * The app screen this section's hands-on step happens on. Sections with one
40 * get a "Try it" button on mobile that opens the app there.
41 */
42 tryIt?: LinkOptions;
43 /**
44 * The app actions that count as doing this section's hands-on step; the
45 * first one that happens marks the section done (see `section-progress.ts`).
46 */
47 doneWhen?: AppActionMatcher[];
48 content: ReactNode;
50​
51export const DOCS = {
52 overview: "https://tanstack.com/db/latest/docs/overview",
53 liveQueries: "https://tanstack.com/db/latest/docs/guides/live-queries",
54 mutations: "https://tanstack.com/db/latest/docs/guides/mutations",
55 concurrentTransactions:
56 "https://tanstack.com/db/latest/docs/guides/mutations#concurrent-optimistic-transactions",
57 queryCollection: "https://tanstack.com/db/latest/docs/collections/query-collection",
58 github: "https://github.com/TanStack/db",
59} as const;
60​
61function External({ href, children }: { href: string; children: ReactNode }) {
62 return (
63 <a href={href} target="_blank" rel="noreferrer">
64 {children}
65 </a>
66 );
68​
69export const GUIDE_SECTIONS: GuideSectionContent[] = [
70 {
71 id: "introduction",
72 eyebrow: "Start here",
73 title: "A notes app where every view is a query",
74 shortTitle: "Intro",
75 appStates: [{ screen: "/" }],
76 tryIt: linkOptions({ to: "/" }),
77 doneWhen: [{ type: "note.opened" }],
78 content: (
79 <>
80 <p>
81 This guide comes with a small copy of Apple Notes, built with <strong>TanStack DB</strong>
82 .{" "}
83 <ByGuideLayout
84 beside="It's in the browser window next to this guide."
85 inSheet="Tap Try it under a section to open it, and close it to come back here."
86 />
87 </p>
88 <p>
89 There's no real server. The app talks to a fake API that runs in your browser: every
90 request takes half a second, and some changes get rejected, like on a real backend. Each
91 section tells you what to do in the app and what to look for.
92 </p>
93 <p>
94 You can slow the API down or make it fail with the{" "}
95 <ShowMe target="network-controls">network controls</ShowMe>
96 <ByGuideLayout
97 beside=" in the browser's toolbar"
98 inSheet=" (Network, at the top of the app)"
99 />
100 , and watch every request in the{" "}
101 <ShowMe target="request-inspector">request inspector</ShowMe>.
102 </p>
103 <Callout variant="tip">
104 Look around first: open a folder, pick a note, and open Settings from the account at the
105 bottom of the folder list.
106 </Callout>
107 </>
108 ),
109 },
110 {
111 id: "collections",
112 eyebrow: "Step 1",
113 title: "What are collections?",
114 shortTitle: "Collections",
115 appStates: [
116 { screen: "/folders/$folderId", lastAction: { type: "folder.opened", smart: false } },
117 // The macOS layout opens a folder on its first note.
118 {
119 screen: "/folders/$folderId/notes/$noteId",
120 lastAction: { type: "folder.opened", smart: false },
121 },
122 { screen: "/folders/$folderId/notes/$noteId", lastAction: { type: "note.opened" } },
123 ],
124 tryIt: linkOptions({ to: "/" }),
125 doneWhen: [{ type: "folder.opened", smart: false }],
126 content: (
127 <>
128 <p>
129 A collection is a typed set of records that TanStack DB keeps in memory and in sync with
130 your backend. This app has three: folders, notes and your account.
131 </p>
132 <p>
133 Here's the notes collection. <code>queryFn</code> loads every note from the API, and{" "}
134 <code>getKey</code> tells them apart. The <code>schema</code> checks the notes you create
135 and change in the app, before anything is sent. (Notes loaded by <code>queryFn</code> skip
136 it: this app trusts its own API.) The three handlers send your changes to the server;
137 we'll get to them.
138 </p>
139 <SourceSnippet snippet={SNIPPETS.notesCollection} />
140 <p>
141 The <ShowMe target="note-list">note list</ShowMe>, the{" "}
142 <ShowMe target="editor">editor</ShowMe> and the{" "}
143 <ShowMe target="folder-counts">folder counts</ShowMe> all read from this one collection.
144 There's only one copy of each note, so when it changes, every view that shows it changes
145 with it.
146 </p>
147 <Callout variant="tip">
148 Open a folder and edit a note's title. The note's row in the list shows the new title as
149 you type (in the iPhone layout, go back to the list to see it).
150 </Callout>
151 </>
152 ),
153 },
154 {
155 id: "live-queries",
156 eyebrow: "Step 2",
157 title: "Live queries",
158 shortTitle: "Live queries",
159 appStates: [
160 { screen: "/folders/$folderId", lastAction: { type: "folder.opened", smart: true } },
161 {
162 screen: "/folders/$folderId/notes/$noteId",
163 lastAction: { type: "folder.opened", smart: true },
164 },
165 { lastAction: { type: "note.pinned" } },
166 { screen: "/settings", lastAction: { type: "account.updated" } },
167 ],
168 tryIt: linkOptions({ to: "/folders/$folderId", params: { folderId: "all" } }),
169 doneWhen: [{ type: "folder.opened", smart: true }, { type: "note.pinned" }],
170 content: (
171 <>
172 <p>
173 You don't read a collection directly. You ask it questions with live queries, and their
174 results stay up to date on their own.
175 </p>
176 <p>
177 Each folder's list is one live query: the notes in that folder, joined with their folder's
178 name, pinned notes first, then in the order picked in Settings.
179 </p>
180 <SourceSnippet snippet={SNIPPETS.noteListQuery} />
181 <p>
182 Smart folders like All iCloud, Shared and Recently Deleted aren't stored anywhere. Each
183 one is just a different <code>where</code> condition:
184 </p>
185 <SourceSnippet snippet={SNIPPETS.inFolder} />
186 <p>
187 Live queries are fast because they don't run again from scratch when data changes.
188 TanStack DB compiles each query into a pipeline that only processes what changed, so
189 editing one note updates one row of each result, not the whole list.
190 </p>
191 <Callout variant="tip">
192 Open All iCloud and pin a note: right-click it in the list (long-press in the iPhone
193 layout) and choose Pin Note. It moves to Pinned. Then change "Sort notes by" in Settings
194 and save: every list follows.
195 </Callout>
196 </>
197 ),
198 },
199 {
200 id: "optimistic-updates",
201 eyebrow: "Step 3",
202 title: "Optimistic updates",
203 shortTitle: "Optimistic updates",
204 appStates: [
205 { screen: "/folders/$folderId/notes/$noteId", lastAction: { type: "note.edited" } },
206 { lastAction: { type: "note.created" } },
207 { lastAction: { type: "note.moved" } },
208 { lastAction: { type: "note.deleted" } },
209 { lastAction: { type: "note.restored" } },
210 { lastAction: { type: "folder.renamed", status: "applied" } },
211 { lastAction: { type: "network.latency-set" } },
212 ],
213 tryIt: linkOptions({ to: "/folders/$folderId", params: { folderId: "work" } }),
214 doneWhen: [{ type: "note.edited" }, { type: "folder.renamed", status: "confirmed" }],
215 content: (
216 <>
217 <p>
218 When you change something, TanStack DB shows the change straight away and sends it to the
219 server in the background. That's an optimistic update: the app assumes the server will say
220 yes.
221 </p>
222 <p>
223 Renaming a folder is the simplest one. It updates the folder in its collection, and the
224 collection's <code>onUpdate</code> handler sends the change to the server. The function
225 returns the transaction, so a caller can wait for the server if it needs to.
226 </p>
227 <SourceSnippet snippet={SNIPPETS.renameFolder} />
228 <p>
229 Every request to the fake API takes half a second, but typing never waits for one. The
230 editor doesn't send a request for each key you press, either. Changes to a note go through
231 a <em>paced mutation</em>: each change shows up at once, and they're saved together when
232 you pause.
233 </p>
234 <SourceSnippet snippet={SNIPPETS.noteChanges} />
235 <h3>Why one paced mutation per note?</h3>
236 <p>
237 TanStack DB lets several changes be in flight at once. Each one that hasn't been saved yet
238 puts its own copy of the whole note on top of what the server last sent. If a newer change
239 finishes first, an older one that's still saving shows its copy again, so an old title can
240 come back for a moment. That's how TanStack DB is designed, not a bug: see{" "}
241 <External href={DOCS.concurrentTransactions}>concurrent optimistic transactions</External>
242 .
243 </p>
244 <p>
245 This app avoids it by sending every change to a note (typing, pinning, moving, deleting)
246 through the same paced mutation, <code>changeNote</code>, built with{" "}
247 <code>pacedPerRecord</code>. Its saves go out one at a time, in order, so a newer change
248 never sits under an older one.
249 </p>
250 <Callout variant="tip">
251 Type in a note: the list keeps up with every key. Then move a note to another folder from
252 its right-click (or long-press) menu: both folders' counts change at once, before the
253 server has answered.
254 </Callout>
255 <Callout variant="tip">
256 Set the latency to 5 s in the <ShowMe target="network-controls">network controls</ShowMe>{" "}
257 and do it again. The app is just as fast; only the{" "}
258 <ShowMe target="request-inspector">request inspector</ShowMe> shows each save waiting five
259 seconds for the server.
260 </Callout>
261 </>
262 ),
263 },
264 {
265 id: "rollbacks",
266 eyebrow: "Step 4",
267 title: "Rollbacks",
268 shortTitle: "Rollbacks",
269 appStates: [
270 { lastAction: { status: "rolled-back" } },
271 { lastAction: { type: "network.fail-next-set", failNext: true } },
272 ],
273 tryIt: linkOptions({ to: "/" }),
274 doneWhen: [{ status: "rolled-back" }],
275 content: (
276 <>
277 <p>
278 Sometimes the server says no. The fake API won't let two folders have the same name, just
279 like a real backend would check:
280 </p>
281 <SourceSnippet snippet={SNIPPETS.duplicateName} />
282 <p>
283 By then the new name is already on screen, so TanStack DB has to undo it. It does that
284 when the collection's handler throws. The handlers call the API through a small client
285 that throws for any error response:
286 </p>
287 <SourceSnippet snippet={SNIPPETS.throwOnError} />
288 <p>
289 The error fails the transaction, and TanStack DB drops its optimistic changes: the folder
290 gets its old name back. No component had to remember the old name.
291 </p>
292 <Callout variant="warning">
293 <code>fetch</code> doesn't throw for 4xx or 5xx responses. If your handler doesn't check{" "}
294 <code>response.ok</code> and throw, TanStack DB treats a failed save as a success.
295 </Callout>
296 <Callout variant="tip">
297 Rename the Work folder to "Personal". In the sidebar, double-click Work or right-click it
298 and choose Rename Folder. In the iPhone layout, tap Edit on the Folders screen, then tap
299 Work. The new name shows up, then switches back, and a message tells you why. A note title
300 longer than {NOTE_TITLE_MAX_LENGTH} characters gets rejected too.
301 </Callout>
302 <Callout variant="tip">
303 Any change can fail. Turn on "Fail next" in the{" "}
304 <ShowMe target="network-controls">network controls</ShowMe>, then pin a note or edit one:
305 the server answers the next request the app sends with a 500, and your change rolls back.
306 Set the latency to 2 s first to watch the change sit on screen while the request is
307 pending.
308 </Callout>
309 </>
310 ),
311 },
312 {
313 id: "sync",
314 eyebrow: "Step 5",
315 title: "How collections sync",
316 shortTitle: "Syncing",
317 appStates: [{ lastAction: { status: "confirmed" } }, { panel: "inspector" }],
318 content: (
319 <>
320 <p>
321 Data in this app flows one way: from the server into collections, from collections into
322 live queries, and from live queries into components. Components never change what they
323 show. They change a collection, and the change flows down from there, on top of the
324 server's data until the server answers.
325 </p>
326 <p>
327 The collections here are <em>query collections</em>, from{" "}
328 <code>@tanstack/query-db-collection</code>. They load data with a TanStack Query{" "}
329 <code>queryFn</code>. Saving doesn't refetch anything: each handler writes the record the
330 server sent back into the collection, so the collection holds exactly what the server
331 saved.
332 </p>
333 <SourceSnippet snippet={SNIPPETS.saveNoteUpdates} />
334 <p>
335 <code>inOrder</code> sends one note's requests one at a time, so an older save can't
336 arrive after a newer one. <code>saveEach</code> saves every record in the transaction,
337 even if one of them fails. Open the{" "}
338 <ShowMe target="request-inspector">request inspector</ShowMe> and type in a note: each
339 pause sends one <code>PATCH</code>, and its response is the note the collection now holds.
340 </p>
341 <p>
342 Query collections work with any REST or RPC API. Other collection types change how data
343 syncs, and keep the rest (live queries, optimistic updates, rollbacks) the same:
344 </p>
345 <ul>
346 <li>
347 Electric (<code>electricCollectionOptions</code>): real-time sync from Postgres
348 </li>
349 <li>PowerSync, RxDB and TrailBase, for offline-first and streaming backends</li>
350 <li>
351 Local-only, localStorage and IndexedDB collections, for data that stays in the browser
352 </li>
353 </ul>
354 <Callout variant="note">
355 The <Link to="/deep-dives/query-driven-sync">query-driven sync</Link> deep dive goes
356 further: it loads only the notes a query needs.
357 </Callout>
358 </>
359 ),
360 },
361 {
362 id: "aggregations",
363 eyebrow: "Step 6",
364 title: "Aggregations",
365 shortTitle: "Aggregations",
366 appStates: [{ screen: "/analytics" }],
367 tryIt: linkOptions({ to: "/analytics" }),
368 content: (
369 <>
370 <p>
371 Live queries can group and count, too. The folder counts in the sidebar come from a{" "}
372 <code>groupBy</code> with <code>count</code>:
373 </p>
374 <SourceSnippet snippet={SNIPPETS.noteCountsQuery} />
375 <p>
376 The Analytics page, at the bottom of the folder list, also adds up the words in each
377 folder. The query builder has no function that counts words, so a first live query works
378 out each note's numbers with <code>fn.select</code>, which runs plain JavaScript:
379 </p>
380 <SourceSnippet snippet={SNIPPETS.noteStatsCollection} />
381 <p>A live query is a collection itself, so a second query can group the first one:</p>
382 <SourceSnippet snippet={SNIPPETS.folderStatsQuery} />
383 <p>
384 Like every live query, these update step by step. When you type in a note, only that
385 note's numbers are worked out again, and only its folder's total changes. This chart reads
386 the same query:
387 </p>
388 <LiveWordsChart />
389 <Callout variant="tip">
390 <ByGuideLayout
391 beside="Type a few words in a note and watch its folder's bar grow. Then open "
392 inSheet="Add a few words to a note, then come back here: its folder's bar has grown. Then open "
393 />
394 <ShowMe target="analytics">Analytics</ShowMe>: the same queries, drawn with TanStack
395 Charts, as notes per folder, words per folder and notes by day of last edit.
396 </Callout>
397 </>
398 ),
399 },
400 {
401 id: "whats-next",
402 eyebrow: "Wrap-up",
403 title: "What's next",
404 shortTitle: "What's next",
405 appStates: [],
406 content: (
407 <>
408 <p>
409 That's the core of TanStack DB: collections hold your data, live queries read it,
410 optimistic mutations change it, and rejected changes roll back on their own.
411 </p>
412 <h3>Deep dives</h3>
413 <ul>
414 <li>
415 <Link to="/deep-dives/query-driven-sync">Query-driven sync</Link>: load only the notes a
416 live query asks for, with <code>syncMode: "on-demand"</code>.
417 </li>
418 </ul>
419 <h3>Docs</h3>
420 <ul>
421 <li>
422 <External href={DOCS.overview}>TanStack DB overview</External>
423 </li>
424 <li>
425 <External href={DOCS.liveQueries}>Live queries</External>
426 </li>
427 <li>
428 <External href={DOCS.mutations}>Mutations</External>
429 </li>
430 <li>
431 <External href={DOCS.queryCollection}>Query collections</External>
432 </li>
433 <li>
434 <External href={DOCS.github}>TanStack DB on GitHub</External>
435 </li>
436 </ul>
437 </>
438 ),
439 },
440];