Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

schemas.md

1,167 lines31.1 KB

1---
2title: Schemas
3id: schemas
4---
5​
6TanStack DB uses schemas to ensure your data is valid and type-safe throughout your application.
7​
8## What You'll Learn
9​
10This guide covers:
11- How schema validation works in TanStack DB
12- Understanding TInput and TOutput types
13- Common patterns: validation, transformations, and defaults
14- Error handling and best practices
15​
16## Quick Example
17​
18Schemas catch invalid data from optimistic mutations before it enters your collection:
19​
20```typescript
21import { z } from 'zod'
22import { createCollection } from '@tanstack/react-db'
23import { queryCollectionOptions } from '@tanstack/query-db-collection'
24​
25const todoSchema = z.object({
26 id: z.string(),
27 text: z.string().min(1, "Text is required"),
28 completed: z.boolean(),
29 priority: z.number().min(0).max(5)
30})
31​
32const collection = createCollection(
33 queryCollectionOptions({
34 schema: todoSchema,
35 queryKey: ['todos'],
36 queryFn: async () => api.todos.getAll(),
37 getKey: (item) => item.id,
38 // ...
39 })
41​
42// Invalid data throws SchemaValidationError
43collection.insert({
44 id: "1",
45 text: "", // ❌ Too short
46 completed: "yes", // ❌ Wrong type
47 priority: 10 // ❌ Out of range
48})
49// Error: Validation failed with 3 issues
50​
51// Valid data works
52collection.insert({
53 id: "1",
54 text: "Buy groceries", // ✅
55 completed: false, // ✅
56 priority: 2 // ✅
57})
58```
59​
60Schemas also enable advanced features like type transformations and defaults:
61​
62```typescript
63const todoSchema = z.object({
64 id: z.string(),
65 text: z.string().min(1),
66 completed: z.boolean().default(false), // Auto-fill missing values
67 created_at: z.string().transform(val => new Date(val)) // Convert types
68})
69​
70collection.insert({
71 id: "1",
72 text: "Buy groceries",
73 created_at: "2024-01-01T00:00:00Z" // String in
74 // completed auto-filled with false
75})
76​
77const todo = collection.get("1")
78console.log(todo.created_at.getFullYear()) // Date object out!
79```
80​
81## Supported Schema Libraries
82​
83TanStack DB supports any [StandardSchema](https://standardschema.dev) compatible library:
84- [Zod](https://zod.dev)
85- [Valibot](https://valibot.dev)
86- [ArkType](https://arktype.io)
87- [Effect Schema](https://effect.website/docs/schema/introduction/)
88​
89Examples in this guide use Zod, but patterns apply to all libraries.
90​
91---
92​
93## Core Concepts: TInput vs TOutput
94​
95Understanding TInput and TOutput is key to working effectively with schemas in TanStack DB.
96​
97> **Important:** Schemas validate **client changes only** - data you insert or update via `collection.insert()` and `collection.update()`. They do not automatically validate data loaded from your server or sync layer. If you need to validate server data, you must do so explicitly in your integration layer.
98​
99### What are TInput and TOutput?
100​
101When you define a schema with transformations, it has two types:
102​
103- **TInput**: The type users provide when calling `insert()` or `update()`
104- **TOutput**: The type stored in the collection and returned from queries
105​
106```typescript
107const todoSchema = z.object({
108 id: z.string(),
109 text: z.string(),
110 created_at: z.string().transform(val => new Date(val))
111})
112​
113// TInput type: { id: string, text: string, created_at: string }
114// TOutput type: { id: string, text: string, created_at: Date }
115```
116​
117The schema acts as a **boundary** that transforms TInput → TOutput.
118​
119### Critical Design Principle: TInput Must Be a Superset of TOutput
120​
121When using transformations, **TInput must accept all values that TOutput contains**. This is essential for updates to work correctly.
122​
123Here's why: when you call `collection.update(id, (draft) => {...})`, the `draft` parameter is typed as `TInput` but contains data that's already been transformed to `TOutput`. For this to work without complex type gymnastics, your schema must accept both the input format AND the output format.
124​
125```typescript
126// ❌ BAD: TInput only accepts strings
127const schema = z.object({
128 created_at: z.string().transform(val => new Date(val))
129})
130// TInput: { created_at: string }
131// TOutput: { created_at: Date }
132// Problem: draft.created_at is a Date, but TInput only accepts string!
133​
134// ✅ GOOD: TInput accepts both string and Date (superset of TOutput)
135const schema = z.object({
136 created_at: z.union([z.string(), z.date()])
137 .transform(val => typeof val === 'string' ? new Date(val) : val)
138})
139// TInput: { created_at: string | Date }
140// TOutput: { created_at: Date }
141// Success: draft.created_at can be a Date because TInput accepts Date!
142```
143​
144**Rule of thumb:** If your schema transforms type A to type B, use `z.union([A, B])` to ensure TInput accepts both.
145​
146### Why This Matters
147​
148**All data in your collection is TOutput:**
149- Data stored in the collection
150- Data returned from queries
151- Data in `PendingMutation.modified`
152- Data in mutation handlers
153​
154```typescript
155const collection = createCollection({
156 schema: todoSchema,
157 onInsert: async ({ transaction }) => {
158 const item = transaction.mutations[0].modified
159​
160 // item is TOutput
161 console.log(item.created_at instanceof Date) // true
162​
163 // If your API needs a string, serialize it
164 await api.todos.create({
165 ...item,
166 created_at: item.created_at.toISOString() // Date → string
167 })
168 }
169})
170​
171// User provides TInput
172collection.insert({
173 id: "1",
174 text: "Task",
175 created_at: "2024-01-01T00:00:00Z" // string
176})
177​
178// Collection stores and returns TOutput
179const todo = collection.get("1")
180console.log(todo.created_at.getFullYear()) // It's a Date!
181```
182​
183## Codecs (Zod 4.1+)
184​
185[Zod codecs](https://zod.dev/codecs) define transformations in both directions. For example, a codec can decode an ISO datetime string into a `Date` and encode that `Date` back into a string for your API.
186​
187As with other transformations, the codec's input must accept its output values. Include `z.date()` in the input so that updates can validate dates already stored in the collection, even when only an unrelated field changes.
188​
189```typescript
190import { z } from 'zod'
191​
192const dateCodec = z.codec(
193 z.union([z.iso.datetime(), z.date()]),
194 z.date(),
195 {
196 decode: (value) => typeof value === 'string' ? new Date(value) : value,
197 encode: (value) => value.toISOString(),
198 }
200​
201const todoApiSchema = z.object({
202 id: z.string(),
203 text: z.string(),
204 created_at: z.iso.datetime(),
205})
206​
207const todoSchema = todoApiSchema.extend({
208 created_at: dateCodec,
209})
210// TInput: { id: string, text: string, created_at: string | Date }
211// TOutput: { id: string, text: string, created_at: Date }
212```
213​
214TanStack DB uses the codec's forward transformation when validating inserts and updates. It does not automatically decode server data or encode outgoing mutations. For a Query Collection, decode server rows in `queryFn` and call `z.encode()` in your mutation handler:
215​
216```typescript
217import { createCollection } from '@tanstack/db'
218import { queryCollectionOptions } from '@tanstack/query-db-collection'
219import { QueryClient } from '@tanstack/query-core'
220​
221const collection = createCollection(
222 queryCollectionOptions({
223 schema: todoSchema,
224 queryKey: ['todos'],
225 queryClient: new QueryClient(),
226 queryFn: async () => todoSchema.array().parse(await api.todos.getAll()),
227 getKey: (todo) => todo.id,
228 onInsert: async ({ transaction, collection }) => {
229 for (const mutation of transaction.mutations) {
230 const payload = todoApiSchema.parse(
231 z.encode(todoSchema, mutation.modified)
232 )
233 await api.todos.create(payload)
234 }
235 await collection.utils.refetch()
236 },
237 })
239```
240​
241`z.encode()` returns the codec's input type, so TypeScript still sees `created_at` as `string | Date`. Parsing the encoded payload with `todoApiSchema` validates the API format and narrows that field to `string`.
242​
243Use the same `z.encode(todoSchema, mutation.modified)` call in `onUpdate` when your API accepts a full row. The full schema requires every field, so it cannot encode a partial `mutation.changes` object.
244​
245For JSON Schema, export `todoApiSchema` with `z.toJSONSchema(todoApiSchema)`. The collection's date codec contains `z.date()` on both sides, so exporting `todoSchema` throws for both input and output conversion.
246​
247See Zod's [codec examples](https://zod.dev/codecs#useful-codecs) for other conversions, and adapt their input schemas to accept the values stored in your collection.
248​
249---
250​
251## Validation Patterns
252​
253Schemas provide powerful validation to ensure data quality.
254​
255### Basic Type Validation
256​
257```typescript
258const userSchema = z.object({
259 id: z.string(),
260 name: z.string(),
261 age: z.number(),
262 email: z.string().email(),
263 active: z.boolean()
264})
265​
266collection.insert({
267 id: "1",
268 name: "Alice",
269 age: "25", // ❌ Wrong type - expects number
270 email: "not-an-email", // ❌ Invalid email format
271 active: true
272})
273// Throws SchemaValidationError
274```
275​
276### String Constraints
277​
278```typescript
279const productSchema = z.object({
280 id: z.string(),
281 name: z.string().min(3, "Name must be at least 3 characters"),
282 sku: z.string().length(8, "SKU must be exactly 8 characters"),
283 description: z.string().max(500, "Description too long"),
284 url: z.string().url("Must be a valid URL")
285})
286```
287​
288### Number Constraints
289​
290```typescript
291const orderSchema = z.object({
292 id: z.string(),
293 quantity: z.number()
294 .int("Must be a whole number")
295 .positive("Must be greater than 0"),
296 price: z.number()
297 .min(0.01, "Price must be at least $0.01")
298 .max(999999.99, "Price too high"),
299 discount: z.number()
300 .min(0)
301 .max(100)
302})
303```
304​
305### Enum Validation
306​
307```typescript
308const taskSchema = z.object({
309 id: z.string(),
310 status: z.enum(['todo', 'in-progress', 'done']),
311 priority: z.enum(['low', 'medium', 'high', 'urgent'])
312})
313​
314collection.insert({
315 id: "1",
316 status: "completed", // ❌ Not in enum
317 priority: "medium" // ✅
318})
319```
320​
321### Optional and Nullable Fields
322​
323```typescript
324const personSchema = z.object({
325 id: z.string(),
326 name: z.string(),
327 nickname: z.string().optional(), // Can be omitted
328 middleName: z.string().nullable(), // Can be null
329 bio: z.string().optional().nullable() // Can be omitted OR null
330})
331​
332// All valid:
333collection.insert({ id: "1", name: "Alice" }) // nickname omitted
334collection.insert({ id: "2", name: "Bob", middleName: null })
335collection.insert({ id: "3", name: "Carol", bio: null })
336```
337​
338### Array Validation
339​
340```typescript
341const postSchema = z.object({
342 id: z.string(),
343 title: z.string(),
344 tags: z.array(z.string()).min(1, "At least one tag required"),
345 likes: z.array(z.number()).max(1000)
346})
347​
348collection.insert({
349 id: "1",
350 title: "My Post",
351 tags: [], // ❌ Need at least one
352 likes: [1, 2, 3]
353})
354```
355​
356### Custom Validation
357​
358```typescript
359const userSchema = z.object({
360 id: z.string(),
361 username: z.string()
362 .min(3)
363 .refine(
364 (val) => /^[a-zA-Z0-9_]+$/.test(val),
365 "Username can only contain letters, numbers, and underscores"
366 ),
367 password: z.string()
368 .min(8)
369 .refine(
370 (val) => /[A-Z]/.test(val) && /[0-9]/.test(val),
371 "Password must contain at least one uppercase letter and one number"
372 )
373})
374```
375​
376### Cross-Field Validation
377​
378```typescript
379const dateRangeSchema = z.object({
380 id: z.string(),
381 start_date: z.string(),
382 end_date: z.string()
383}).refine(
384 (data) => new Date(data.end_date) > new Date(data.start_date),
385 "End date must be after start date"
387```
388​
389---
390​
391## Transformation Patterns
392​
393Schemas can transform data as it enters your collection.
394​
395### String to Date
396​
397The most common transformation - convert ISO strings to Date objects:
398​
399```typescript
400const eventSchema = z.object({
401 id: z.string(),
402 name: z.string(),
403 start_time: z.string().transform(val => new Date(val))
404})
405​
406collection.insert({
407 id: "1",
408 name: "Conference",
409 start_time: "2024-06-15T10:00:00Z" // TInput: string
410})
411​
412const event = collection.get("1")
413console.log(event.start_time.getFullYear()) // TOutput: Date
414```
415​
416### String to Number
417​
418```typescript
419const formSchema = z.object({
420 id: z.string(),
421 quantity: z.string().transform(val => parseInt(val, 10)),
422 price: z.string().transform(val => parseFloat(val))
423})
424​
425collection.insert({
426 id: "1",
427 quantity: "42", // String from form input
428 price: "19.99"
429})
430​
431const item = collection.get("1")
432console.log(typeof item.quantity) // "number"
433```
434​
435### JSON String to Object
436​
437```typescript
438const configSchema = z.object({
439 id: z.string(),
440 settings: z.string().transform(val => JSON.parse(val))
441})
442​
443collection.insert({
444 id: "1",
445 settings: '{"theme":"dark","notifications":true}' // JSON string
446})
447​
448const config = collection.get("1")
449console.log(config.settings.theme) // "dark" (parsed object)
450```
451​
452### Computed Fields
453​
454```typescript
455const userSchema = z.object({
456 id: z.string(),
457 first_name: z.string(),
458 last_name: z.string()
459}).transform(data => ({
460 ...data,
461 full_name: `${data.first_name} ${data.last_name}` // Computed
462}))
463​
464collection.insert({
465 id: "1",
466 first_name: "John",
467 last_name: "Doe"
468})
469​
470const user = collection.get("1")
471console.log(user.full_name) // "John Doe"
472```
473​
474### String to Enum
475​
476```typescript
477const orderSchema = z.object({
478 id: z.string(),
479 status: z.string().transform(val =>
480 val.toUpperCase() as 'PENDING' | 'SHIPPED' | 'DELIVERED'
481 )
482})
483```
484​
485### Sanitization
486​
487```typescript
488const commentSchema = z.object({
489 id: z.string(),
490 text: z.string().transform(val => val.trim()), // Remove whitespace
491 username: z.string().transform(val => val.toLowerCase()) // Normalize
492})
493```
494​
495### Complex Transformations
496​
497```typescript
498const productSchema = z.object({
499 id: z.string(),
500 name: z.string(),
501 price_cents: z.number()
502}).transform(data => ({
503 ...data,
504 price_dollars: data.price_cents / 100, // Add computed field
505 display_price: `$${(data.price_cents / 100).toFixed(2)}` // Formatted
506}))
507```
508​
509---
510​
511## Default Values
512​
513Schemas can automatically provide default values for missing fields.
514​
515### Literal Defaults
516​
517```typescript
518const todoSchema = z.object({
519 id: z.string(),
520 text: z.string(),
521 completed: z.boolean().default(false),
522 priority: z.number().default(0),
523 tags: z.array(z.string()).default([])
524})
525​
526collection.insert({
527 id: "1",
528 text: "Buy groceries"
529 // completed, priority, and tags filled automatically
530})
531​
532const todo = collection.get("1")
533console.log(todo.completed) // false
534console.log(todo.priority) // 0
535console.log(todo.tags) // []
536```
537​
538### Function Defaults
539​
540Generate defaults dynamically:
541​
542```typescript
543const postSchema = z.object({
544 id: z.string(),
545 title: z.string(),
546 created_at: z.date().default(() => new Date()),
547 view_count: z.number().default(0),
548 slug: z.string().default(() => crypto.randomUUID())
549})
550​
551collection.insert({
552 id: "1",
553 title: "My First Post"
554 // created_at, view_count, and slug generated automatically
555})
556```
557​
558### Conditional Defaults
559​
560```typescript
561const userSchema = z.object({
562 id: z.string(),
563 username: z.string(),
564 role: z.enum(['user', 'admin']).default('user'),
565 permissions: z.array(z.string()).default(['read'])
566})
567```
568​
569### Complex Defaults
570​
571```typescript
572const eventSchema = z.object({
573 id: z.string(),
574 name: z.string(),
575 metadata: z.record(z.unknown()).default(() => ({
576 created_by: 'system',
577 version: 1
578 }))
579})
580```
581​
582### Combining Defaults with Transformations
583​
584```typescript
585const todoSchema = z.object({
586 id: z.string(),
587 text: z.string(),
588 completed: z.boolean().default(false),
589 created_at: z.string()
590 .default(() => new Date().toISOString())
591 .transform(val => new Date(val))
592})
593​
594collection.insert({
595 id: "1",
596 text: "Task"
597 // completed defaults to false
598 // created_at defaults to current time, then transforms to Date
599})
600```
601​
602---
603​
604## Handling Timestamps
605​
606When working with timestamps, you typically want automatic creation dates rather than transforming user input.
607​
608### Use Defaults for Timestamps
609​
610For `created_at` and `updated_at` fields, use defaults to automatically generate timestamps:
611​
612```typescript
613const todoSchema = z.object({
614 id: z.string(),
615 text: z.string(),
616 completed: z.boolean().default(false),
617 created_at: z.date().default(() => new Date()),
618 updated_at: z.date().default(() => new Date())
619})
620​
621// Timestamps generated automatically
622collection.insert({
623 id: "1",
624 text: "Buy groceries"
625 // created_at and updated_at filled automatically
626})
627​
628// Update timestamps
629collection.update("1", (draft) => {
630 draft.text = "Buy groceries and milk"
631 draft.updated_at = new Date()
632})
633```
634​
635### Accepting Date Input from External Sources
636​
637If you're accepting date input from external sources (forms, APIs), you must use union types to accept both strings and Date objects. This ensures TInput is a superset of TOutput:
638​
639```typescript
640const eventSchema = z.object({
641 id: z.string(),
642 name: z.string(),
643 scheduled_for: z.union([
644 z.string(), // Accept ISO string from form input (part of TInput)
645 z.date() // Accept Date from existing data (TOutput) or programmatic input
646 ]).transform(val =>
647 typeof val === 'string' ? new Date(val) : val
648 )
649})
650// TInput: { scheduled_for: string | Date }
651// TOutput: { scheduled_for: Date }
652// ✅ TInput is a superset of TOutput (accepts both string and Date)
653​
654// Works with string input (new data)
655collection.insert({
656 id: "1",
657 name: "Meeting",
658 scheduled_for: "2024-12-31T15:00:00Z" // From form input
659})
660​
661// Works with Date input (programmatic)
662collection.insert({
663 id: "2",
664 name: "Workshop",
665 scheduled_for: new Date()
666})
667​
668// Updates work - scheduled_for is already a Date, and TInput accepts Date
669collection.update("1", (draft) => {
670 draft.name = "Updated Meeting"
671 // draft.scheduled_for is a Date and can be used or modified
672})
673```
674​
675---
676​
677## Error Handling
678​
679When validation fails, TanStack DB throws a `SchemaValidationError` with detailed information.
680​
681### Basic Error Handling
682​
683```typescript
684import { SchemaValidationError } from '@tanstack/db'
685​
686try {
687 collection.insert({
688 id: "1",
689 email: "not-an-email",
690 age: -5
691 })
692} catch (error) {
693 if (error instanceof SchemaValidationError) {
694 console.log(error.type) // 'insert' or 'update'
695 console.log(error.message) // "Validation failed with 2 issues"
696 console.log(error.issues) // Array of validation issues
697 }
699```
700​
701### Error Structure
702​
703```typescript
704error.issues = [
705 {
706 path: ['email'],
707 message: 'Invalid email address'
708 },
709 {
710 path: ['age'],
711 message: 'Number must be greater than 0'
712 }
714```
715​
716### Displaying Errors in UI
717​
718```typescript
719const handleSubmit = async (data: unknown) => {
720 try {
721 collection.insert(data)
722 } catch (error) {
723 if (error instanceof SchemaValidationError) {
724 // Show errors by field
725 error.issues.forEach(issue => {
726 const fieldName = issue.path?.join('.') || 'unknown'
727 showFieldError(fieldName, issue.message)
728 })
729 }
730 }
732```
733​
734### React Example
735​
736```tsx
737import { SchemaValidationError } from '@tanstack/db'
738​
739function TodoForm() {
740 const [errors, setErrors] = useState<Record<string, string>>({})
741​
742 const handleSubmit = (e: React.FormEvent) => {
743 e.preventDefault()
744 setErrors({})
745​
746 try {
747 todoCollection.insert({
748 id: crypto.randomUUID(),
749 text: e.currentTarget.text.value,
750 priority: parseInt(e.currentTarget.priority.value)
751 })
752 } catch (error) {
753 if (error instanceof SchemaValidationError) {
754 const newErrors: Record<string, string> = {}
755 error.issues.forEach(issue => {
756 const field = issue.path?.[0] || 'form'
757 newErrors[field] = issue.message
758 })
759 setErrors(newErrors)
760 }
761 }
762 }
763​
764 return (
765 <form onSubmit={handleSubmit}>
766 <input name="text" />
767 {errors.text && <span className="error">{errors.text}</span>}
768​
769 <input name="priority" type="number" />
770 {errors.priority && <span className="error">{errors.priority}</span>}
771​
772 <button type="submit">Add Todo</button>
773 </form>
774 )
776```
777​
778---
779​
780## Best Practices
781​
782### Keep Transformations Simple
783​
784> **Performance Note:** Schema validation is synchronous and runs on every optimistic mutation. For high-frequency updates, keep transformations simple.
785​
786```typescript
787// ❌ Avoid expensive operations
788const schema = z.object({
789 data: z.string().transform(val => {
790 // Heavy computation on every mutation
791 return expensiveParsingOperation(val)
792 })
793})
794​
795// ✅ Better: Validate only, process elsewhere
796const schema = z.object({
797 data: z.string() // Simple validation
798})
799​
800// Process in component or mutation handler when needed
801const processedData = expensiveParsingOperation(todo.data)
802```
803​
804### Use Union Types for Transformations (Essential)
805​
806When your schema transforms data to a different type, you **must** use union types to ensure TInput is a superset of TOutput. This is not optional - updates will fail without it.
807​
808```typescript
809// ✅ REQUIRED: TInput accepts both string (new data) and Date (existing data)
810const schema = z.object({
811 created_at: z.union([z.string(), z.date()])
812 .transform(val => typeof val === 'string' ? new Date(val) : val)
813})
814// TInput: { created_at: string | Date }
815// TOutput: { created_at: Date }
816​
817// ❌ WILL BREAK: Updates fail because draft contains Date but TInput only accepts string
818const schema = z.object({
819 created_at: z.string().transform(val => new Date(val))
820})
821// TInput: { created_at: string }
822// TOutput: { created_at: Date }
823// Problem: collection.update() passes a Date to a schema expecting string!
824```
825​
826**Why this is required:** During `collection.update()`, the `draft` object contains TOutput data (already transformed). The schema must accept this data, which means TInput must be a superset of TOutput.
827​
828### Validate at the Boundary
829​
830Let the collection schema handle validation. Don't duplicate validation logic:
831​
832```typescript
833// ❌ Avoid: Duplicate validation
834function addTodo(text: string) {
835 if (!text || text.length < 3) {
836 throw new Error("Text too short")
837 }
838 todoCollection.insert({ id: "1", text })
840​
841// ✅ Better: Let schema handle it
842const todoSchema = z.object({
843 id: z.string(),
844 text: z.string().min(3, "Text must be at least 3 characters")
845})
846```
847​
848### Type Inference
849​
850Let TypeScript infer types from your schema:
851​
852```typescript
853const todoSchema = z.object({
854 id: z.string(),
855 text: z.string(),
856 completed: z.boolean()
857})
858​
859type Todo = z.infer<typeof todoSchema> // Inferred type
860​
861// ✅ Use the inferred type
862const collection = createCollection(
863 queryCollectionOptions({
864 schema: todoSchema,
865 // TypeScript knows the item type automatically
866 getKey: (item) => item.id // item is Todo
867 })
869```
870​
871### Custom Error Messages
872​
873Provide helpful error messages for users:
874​
875```typescript
876const userSchema = z.object({
877 username: z.string()
878 .min(3, "Username must be at least 3 characters")
879 .max(20, "Username is too long (max 20 characters)")
880 .regex(/^[a-zA-Z0-9_]+$/, "Username can only contain letters, numbers, and underscores"),
881 email: z.string().email("Please enter a valid email address"),
882 age: z.number()
883 .int("Age must be a whole number")
884 .min(13, "You must be at least 13 years old")
885})
886```
887​
888---
889​
890## Full-Context Examples
891​
892### Example 1: Todo App with Rich Types
893​
894A complete todo application demonstrating validation, transformations, and defaults:
895​
896```typescript
897import { z } from 'zod'
898import { createCollection, useLiveQuery } from '@tanstack/react-db'
899import { not, SchemaValidationError } from '@tanstack/db'
900import { queryCollectionOptions } from '@tanstack/query-db-collection'
901​
902// Schema with validation, transformations, and defaults
903const todoSchema = z.object({
904 id: z.string(),
905 text: z.string().min(1, "Todo text cannot be empty"),
906 completed: z.boolean().default(false),
907 priority: z.enum(['low', 'medium', 'high']).default('medium'),
908 due_date: z.union([
909 z.string(),
910 z.date()
911 ]).transform(val => typeof val === 'string' ? new Date(val) : val).optional(),
912 created_at: z.union([
913 z.string(),
914 z.date()
915 ]).transform(val => typeof val === 'string' ? new Date(val) : val)
916 .default(() => new Date()),
917 tags: z.array(z.string()).default([])
918})
919​
920type Todo = z.infer<typeof todoSchema>
921​
922// Collection setup
923const todoCollection = createCollection(
924 queryCollectionOptions({
925 queryKey: ['todos'],
926 queryFn: async () => {
927 const response = await fetch('/api/todos')
928 const todos = await response.json()
929 // Reuse schema to parse and transform API responses
930 return todos.map((todo: any) => todoSchema.parse(todo))
931 },
932 getKey: (item) => item.id,
933 schema: todoSchema,
934 queryClient,
935​
936 onInsert: async ({ transaction, collection }) => {
937 const todo = transaction.mutations[0].modified
938​
939 // Serialize dates for API
940 await fetch('/api/todos', {
941 method: 'POST',
942 headers: { 'Content-Type': 'application/json' },
943 body: JSON.stringify({
944 ...todo,
945 due_date: todo.due_date?.toISOString(),
946 created_at: todo.created_at.toISOString()
947 })
948 })
949 await collection.utils.refetch()
950 },
951​
952 onUpdate: async ({ transaction, collection }) => {
953 await Promise.all(
954 transaction.mutations.map(async (mutation) => {
955 const { original, changes } = mutation
956​
957 // Serialize any date fields in changes
958 const serialized = {
959 ...changes,
960 due_date: changes.due_date instanceof Date
961 ? changes.due_date.toISOString()
962 : changes.due_date
963 }
964​
965 await fetch(`/api/todos/${original.id}`, {
966 method: 'PATCH',
967 headers: { 'Content-Type': 'application/json' },
968 body: JSON.stringify(serialized)
969 })
970 })
971 )
972 await collection.utils.refetch()
973 },
974​
975 onDelete: async ({ transaction, collection }) => {
976 await Promise.all(
977 transaction.mutations.map(async (mutation) => {
978 await fetch(`/api/todos/${mutation.original.id}`, {
979 method: 'DELETE'
980 })
981 })
982 )
983 await collection.utils.refetch()
984 }
985 })
987​
988// Component usage
989function TodoApp() {
990 const { data: todos } = useLiveQuery(q =>
991 q.from({ todo: todoCollection })
992 .where(({ todo }) => not(todo.completed))
993 .orderBy(({ todo }) => todo.created_at, 'desc')
994 )
995​
996 const [errors, setErrors] = useState({} as Record<string, string>)
997​
998 const addTodo = (text: string, priority: 'low' | 'medium' | 'high') => {
999 try {
1000 todoCollection.insert({
1001 id: crypto.randomUUID(),
1002 text,
1003 priority,
1004 due_date: "2024-12-31T23:59:59Z"
1005 // completed, created_at, tags filled automatically by defaults
1006 })
1007 setErrors({})
1008 } catch (error) {
1009 if (error instanceof SchemaValidationError) {
1010 const newErrors: Record<string, string> = {}
1011 error.issues.forEach(issue => {
1012 const field = String(issue.path?.[0] ?? 'form')
1013 newErrors[field] = issue.message
1014 })
1015 setErrors(newErrors)
1019​
1020 const toggleComplete = (todo: Todo) => {
1021 todoCollection.update(todo.id, (draft) => {
1022 draft.completed = !draft.completed
1023 })
1025​
1026 return (
1027 <div>
1028 <h1>Todos</h1>
1029​
1030 {errors.text && <div className="error">{errors.text}</div>}
1031​
1032 <button onClick={() => addTodo("Buy groceries", "high")}>
1033 Add Todo
1034 </button>
1035​
1036 <ul>
1037 {todos?.map(todo => (
1038 <li key={todo.id}>
1039 <input
1040 type="checkbox"
1041 checked={todo.completed}
1042 onChange={() => toggleComplete(todo)}
1043 />
1044 <span>{todo.text}</span>
1045 <span>Priority: {todo.priority}</span>
1046 {todo.due_date && (
1047 <span>Due: {todo.due_date.toLocaleDateString()}</span>
1048 )}
1049 <span>Created: {todo.created_at.toLocaleDateString()}</span>
1050 </li>
1051 ))}
1052 </ul>
1053 </div>
1056```
1057​
1058### Example 2: E-commerce Product with Computed Fields
1059​
1060```typescript
1061import { z } from 'zod'
1062​
1063// Schema with computed fields and transformations
1064const productSchema = z.object({
1065 id: z.string(),
1066 name: z.string().min(3, "Product name must be at least 3 characters"),
1067 description: z.string().max(500, "Description too long"),
1068 base_price: z.number().positive("Price must be positive"),
1069 tax_rate: z.number().min(0).max(1).default(0.1),
1070 discount_percent: z.number().min(0).max(100).default(0),
1071 stock: z.number().int().min(0).default(0),
1072 category: z.enum(['electronics', 'clothing', 'food', 'other']),
1073 tags: z.array(z.string()).default([]),
1074 created_at: z.union([z.string(), z.date()])
1075 .transform(val => typeof val === 'string' ? new Date(val) : val)
1076 .default(() => new Date())
1077}).transform(data => ({
1078 ...data,
1079 // Computed fields
1080 final_price: data.base_price * (1 + data.tax_rate) * (1 - data.discount_percent / 100),
1081 in_stock: data.stock > 0,
1082 display_price: `$${(data.base_price * (1 + data.tax_rate) * (1 - data.discount_percent / 100)).toFixed(2)}`
1083}))
1084​
1085type Product = z.infer<typeof productSchema>
1086​
1087const productCollection = createCollection(
1088 queryCollectionOptions({
1089 queryKey: ['products'],
1090 queryFn: async () => api.products.getAll(),
1091 getKey: (item) => item.id,
1092 schema: productSchema,
1093 queryClient,
1094​
1095 onInsert: async ({ transaction, collection }) => {
1096 const product = transaction.mutations[0].modified
1097​
1098 // API only needs base fields, not computed ones
1099 await api.products.create({
1100 name: product.name,
1101 description: product.description,
1102 base_price: product.base_price,
1103 tax_rate: product.tax_rate,
1104 discount_percent: product.discount_percent,
1105 stock: product.stock,
1106 category: product.category,
1107 tags: product.tags
1108 })
1109 await collection.utils.refetch()
1111 })
1113​
1114// Usage
1115function ProductList() {
1116 const { data: products } = useLiveQuery(q =>
1117 q.from({ product: productCollection })
1118 .where(({ product }) => product.in_stock) // Use computed field
1119 .orderBy(({ product }) => product.final_price, 'asc')
1121​
1122 const addProduct = () => {
1123 productCollection.insert({
1124 id: crypto.randomUUID(),
1125 name: "Wireless Mouse",
1126 description: "Ergonomic wireless mouse",
1127 base_price: 29.99,
1128 discount_percent: 10,
1129 category: "electronics",
1130 stock: 50
1131 // tax_rate, tags, created_at filled by defaults
1132 // final_price, in_stock, display_price computed automatically
1133 })
1135​
1136 return (
1137 <div>
1138 {products?.map(product => (
1139 <div key={product.id}>
1140 <h3>{product.name}</h3>
1141 <p>{product.description}</p>
1142 <p>Price: {product.display_price}</p>
1143 <p>Stock: {product.in_stock ? `${product.stock} available` : 'Out of stock'}</p>
1144 <p>Category: {product.category}</p>
1145 </div>
1146 ))}
1147 </div>
1150```
1151​
1152---
1153​
1154## For Integration Authors
1155​
1156If you're building a custom collection (like Electric or TrailBase), you'll need to handle data parsing and serialization between your storage format and the in-memory collection format. This is separate from schema validation, which happens during client mutations.
1157​
1158See the [Collection Options Creator Guide](./collection-options-creator.md) for comprehensive documentation on creating custom collection integrations, including how to handle schemas, data parsing, and type transformations.
1159​
1160---
1161​
1162## Related Topics
1163​
1164- **[Mutations Guide](./mutations.md)** - Learn about optimistic mutations and how schemas validate mutation data
1165- **[Error Handling Guide](./error-handling.md)** - Comprehensive guide to handling `SchemaValidationError` and other errors
1166- **[Collection Options Creator Guide](./collection-options-creator.md)** - For integration authors: creating custom collection types with schema support
1167- **[StandardSchema Specification](https://standardschema.dev)** - Full specification for StandardSchema v1