Open History to see the last commit
1import { DbClient, collectionOptions, eq } from '@tanstack/react-db'
2import type { DehydratedDbState } from '@tanstack/react-db'
3
4export type SsrTodo = {
5 id: string
6 text: string
7 status: `open` | `done`
8 source: `server` | `sync` | `stream`
9}
10
11export const ssrTodoCollectionId = `ssr-e2e-todos`
12
13const serverTodos: Array<SsrTodo> = [
14 {
15 id: `server-1`,
16 text: `Pay invoices`,
17 status: `open`,
18 source: `server`,
19 },
20 {
21 id: `server-2`,
22 text: `Review pull requests`,
23 status: `open`,
24 source: `server`,
25 },
26 {
27 id: `server-3`,
28 text: `Archived roadmap`,
29 status: `done`,
30 source: `server`,
31 },
32]
33
34const browserTodos: Array<SsrTodo> = serverTodos.map((todo) =>
35 todo.id === `server-1`
36 ? {
37 ...todo,
38 text: `Pay invoices (reconciled from sync)`,
39 source: `sync`,
40 }
41 : { ...todo, source: `sync` },
42)
43
44export const streamedTodo: SsrTodo = {
45 id: `streamed-1`,
46 text: `Streamed from collection chunk`,
47 status: `open`,
48 source: `stream`,
49}
50
51export const ssrTodoCollection = collectionOptions(ssrTodoCollectionId, () => ({
52 id: ssrTodoCollectionId,
53 getKey: (todo: SsrTodo) => todo.id,
54 syncMode: `on-demand`,
55 sync: {
56 sync: ({ begin, write, commit, markReady }) => {
57 markReady()
58
59 return {
60 loadSubset: () => {
61 const todos =
62 typeof window === `undefined` ? serverTodos : browserTodos
63
64 begin()
65 for (const todo of todos) {
66 write({
67 type: `insert`,
68 value: todo,
69 })
70 }
71 return commit()
72 },
73 }
74 },
75 },
76}))
77
78export async function preloadSsrTodos(dbClient: DbClient): Promise<void> {
79 await dbClient.preloadLiveQuery({
80 query: (q) =>
81 q
82 .from({ todo: ssrTodoCollection })
83 .where(({ todo }) => eq(todo.status, `open`)),
84 })
85}
86
87export async function createDehydratedSsrTodoState(): Promise<DehydratedDbState> {
88 const dbClient = new DbClient()
89 try {
90 await preloadSsrTodos(dbClient)
91 return dbClient.dehydrate()
92 } finally {
93 await dbClient.cleanup()
94 }
95}
96
97export function applyStreamedTodo(dbClient: DbClient): void {
98 dbClient.applyCollectionChunk({
99 collectionId: ssrTodoCollectionId,
100 rows: [
101 {
102 key: streamedTodo.id,
103 value: streamedTodo,
104 },
105 ],
106 })
107}