Open History to see the last commit
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 })
40)
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---
184
185## Validation Patterns
186
187Schemas provide powerful validation to ensure data quality.
188
189### Basic Type Validation
190
191```typescript
192const userSchema = z.object({
193 id: z.string(),
194 name: z.string(),
195 age: z.number(),
196 email: z.string().email(),
197 active: z.boolean()
198})
199
200collection.insert({
201 id: "1",
202 name: "Alice",
203 age: "25", // ❌ Wrong type - expects number
204 email: "not-an-email", // ❌ Invalid email format
205 active: true
206})
207// Throws SchemaValidationError
208```
209
210### String Constraints
211
212```typescript
213const productSchema = z.object({
214 id: z.string(),
215 name: z.string().min(3, "Name must be at least 3 characters"),
216 sku: z.string().length(8, "SKU must be exactly 8 characters"),
217 description: z.string().max(500, "Description too long"),
218 url: z.string().url("Must be a valid URL")
219})
220```
221
222### Number Constraints
223
224```typescript
225const orderSchema = z.object({
226 id: z.string(),
227 quantity: z.number()
228 .int("Must be a whole number")
229 .positive("Must be greater than 0"),
230 price: z.number()
231 .min(0.01, "Price must be at least $0.01")
232 .max(999999.99, "Price too high"),
233 discount: z.number()
234 .min(0)
235 .max(100)
236})
237```
238
239### Enum Validation
240
241```typescript
242const taskSchema = z.object({
243 id: z.string(),
244 status: z.enum(['todo', 'in-progress', 'done']),
245 priority: z.enum(['low', 'medium', 'high', 'urgent'])
246})
247
248collection.insert({
249 id: "1",
250 status: "completed", // ❌ Not in enum
251 priority: "medium" // ✅
252})
253```
254
255### Optional and Nullable Fields
256
257```typescript
258const personSchema = z.object({
259 id: z.string(),
260 name: z.string(),
261 nickname: z.string().optional(), // Can be omitted
262 middleName: z.string().nullable(), // Can be null
263 bio: z.string().optional().nullable() // Can be omitted OR null
264})
265
266// All valid:
267collection.insert({ id: "1", name: "Alice" }) // nickname omitted
268collection.insert({ id: "2", name: "Bob", middleName: null })
269collection.insert({ id: "3", name: "Carol", bio: null })
270```
271
272### Array Validation
273
274```typescript
275const postSchema = z.object({
276 id: z.string(),
277 title: z.string(),
278 tags: z.array(z.string()).min(1, "At least one tag required"),
279 likes: z.array(z.number()).max(1000)
280})
281
282collection.insert({
283 id: "1",
284 title: "My Post",
285 tags: [], // ❌ Need at least one
286 likes: [1, 2, 3]
287})
288```
289
290### Custom Validation
291
292```typescript
293const userSchema = z.object({
294 id: z.string(),
295 username: z.string()
296 .min(3)
297 .refine(
298 (val) => /^[a-zA-Z0-9_]+$/.test(val),
299 "Username can only contain letters, numbers, and underscores"
300 ),
301 password: z.string()
302 .min(8)
303 .refine(
304 (val) => /[A-Z]/.test(val) && /[0-9]/.test(val),
305 "Password must contain at least one uppercase letter and one number"
306 )
307})
308```
309
310### Cross-Field Validation
311
312```typescript
313const dateRangeSchema = z.object({
314 id: z.string(),
315 start_date: z.string(),
316 end_date: z.string()
317}).refine(
318 (data) => new Date(data.end_date) > new Date(data.start_date),
319 "End date must be after start date"
320)
321```
322
323---
324
325## Transformation Patterns
326
327Schemas can transform data as it enters your collection.
328
329### String to Date
330
331The most common transformation - convert ISO strings to Date objects:
332
333```typescript
334const eventSchema = z.object({
335 id: z.string(),
336 name: z.string(),
337 start_time: z.string().transform(val => new Date(val))
338})
339
340collection.insert({
341 id: "1",
342 name: "Conference",
343 start_time: "2024-06-15T10:00:00Z" // TInput: string
344})
345
346const event = collection.get("1")
347console.log(event.start_time.getFullYear()) // TOutput: Date
348```
349
350### String to Number
351
352```typescript
353const formSchema = z.object({
354 id: z.string(),
355 quantity: z.string().transform(val => parseInt(val, 10)),
356 price: z.string().transform(val => parseFloat(val))
357})
358
359collection.insert({
360 id: "1",
361 quantity: "42", // String from form input
362 price: "19.99"
363})
364
365const item = collection.get("1")
366console.log(typeof item.quantity) // "number"
367```
368
369### JSON String to Object
370
371```typescript
372const configSchema = z.object({
373 id: z.string(),
374 settings: z.string().transform(val => JSON.parse(val))
375})
376
377collection.insert({
378 id: "1",
379 settings: '{"theme":"dark","notifications":true}' // JSON string
380})
381
382const config = collection.get("1")
383console.log(config.settings.theme) // "dark" (parsed object)
384```
385
386### Computed Fields
387
388```typescript
389const userSchema = z.object({
390 id: z.string(),
391 first_name: z.string(),
392 last_name: z.string()
393}).transform(data => ({
394 ...data,
395 full_name: `${data.first_name} ${data.last_name}` // Computed
396}))
397
398collection.insert({
399 id: "1",
400 first_name: "John",
401 last_name: "Doe"
402})
403
404const user = collection.get("1")
405console.log(user.full_name) // "John Doe"
406```
407
408### String to Enum
409
410```typescript
411const orderSchema = z.object({
412 id: z.string(),
413 status: z.string().transform(val =>
414 val.toUpperCase() as 'PENDING' | 'SHIPPED' | 'DELIVERED'
415 )
416})
417```
418
419### Sanitization
420
421```typescript
422const commentSchema = z.object({
423 id: z.string(),
424 text: z.string().transform(val => val.trim()), // Remove whitespace
425 username: z.string().transform(val => val.toLowerCase()) // Normalize
426})
427```
428
429### Complex Transformations
430
431```typescript
432const productSchema = z.object({
433 id: z.string(),
434 name: z.string(),
435 price_cents: z.number()
436}).transform(data => ({
437 ...data,
438 price_dollars: data.price_cents / 100, // Add computed field
439 display_price: `$${(data.price_cents / 100).toFixed(2)}` // Formatted
440}))
441```
442
443---
444
445## Default Values
446
447Schemas can automatically provide default values for missing fields.
448
449### Literal Defaults
450
451```typescript
452const todoSchema = z.object({
453 id: z.string(),
454 text: z.string(),
455 completed: z.boolean().default(false),
456 priority: z.number().default(0),
457 tags: z.array(z.string()).default([])
458})
459
460collection.insert({
461 id: "1",
462 text: "Buy groceries"
463 // completed, priority, and tags filled automatically
464})
465
466const todo = collection.get("1")
467console.log(todo.completed) // false
468console.log(todo.priority) // 0
469console.log(todo.tags) // []
470```
471
472### Function Defaults
473
474Generate defaults dynamically:
475
476```typescript
477const postSchema = z.object({
478 id: z.string(),
479 title: z.string(),
480 created_at: z.date().default(() => new Date()),
481 view_count: z.number().default(0),
482 slug: z.string().default(() => crypto.randomUUID())
483})
484
485collection.insert({
486 id: "1",
487 title: "My First Post"
488 // created_at, view_count, and slug generated automatically
489})
490```
491
492### Conditional Defaults
493
494```typescript
495const userSchema = z.object({
496 id: z.string(),
497 username: z.string(),
498 role: z.enum(['user', 'admin']).default('user'),
499 permissions: z.array(z.string()).default(['read'])
500})
501```
502
503### Complex Defaults
504
505```typescript
506const eventSchema = z.object({
507 id: z.string(),
508 name: z.string(),
509 metadata: z.record(z.unknown()).default(() => ({
510 created_by: 'system',
511 version: 1
512 }))
513})
514```
515
516### Combining Defaults with Transformations
517
518```typescript
519const todoSchema = z.object({
520 id: z.string(),
521 text: z.string(),
522 completed: z.boolean().default(false),
523 created_at: z.string()
524 .default(() => new Date().toISOString())
525 .transform(val => new Date(val))
526})
527
528collection.insert({
529 id: "1",
530 text: "Task"
531 // completed defaults to false
532 // created_at defaults to current time, then transforms to Date
533})
534```
535
536---
537
538## Handling Timestamps
539
540When working with timestamps, you typically want automatic creation dates rather than transforming user input.
541
542### Use Defaults for Timestamps
543
544For `created_at` and `updated_at` fields, use defaults to automatically generate timestamps:
545
546```typescript
547const todoSchema = z.object({
548 id: z.string(),
549 text: z.string(),
550 completed: z.boolean().default(false),
551 created_at: z.date().default(() => new Date()),
552 updated_at: z.date().default(() => new Date())
553})
554
555// Timestamps generated automatically
556collection.insert({
557 id: "1",
558 text: "Buy groceries"
559 // created_at and updated_at filled automatically
560})
561
562// Update timestamps
563collection.update("1", (draft) => {
564 draft.text = "Buy groceries and milk"
565 draft.updated_at = new Date()
566})
567```
568
569### Accepting Date Input from External Sources
570
571If 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:
572
573```typescript
574const eventSchema = z.object({
575 id: z.string(),
576 name: z.string(),
577 scheduled_for: z.union([
578 z.string(), // Accept ISO string from form input (part of TInput)
579 z.date() // Accept Date from existing data (TOutput) or programmatic input
580 ]).transform(val =>
581 typeof val === 'string' ? new Date(val) : val
582 )
583})
584// TInput: { scheduled_for: string | Date }
585// TOutput: { scheduled_for: Date }
586// ✅ TInput is a superset of TOutput (accepts both string and Date)
587
588// Works with string input (new data)
589collection.insert({
590 id: "1",
591 name: "Meeting",
592 scheduled_for: "2024-12-31T15:00:00Z" // From form input
593})
594
595// Works with Date input (programmatic)
596collection.insert({
597 id: "2",
598 name: "Workshop",
599 scheduled_for: new Date()
600})
601
602// Updates work - scheduled_for is already a Date, and TInput accepts Date
603collection.update("1", (draft) => {
604 draft.name = "Updated Meeting"
605 // draft.scheduled_for is a Date and can be used or modified
606})
607```
608
609---
610
611## Error Handling
612
613When validation fails, TanStack DB throws a `SchemaValidationError` with detailed information.
614
615### Basic Error Handling
616
617```typescript
618import { SchemaValidationError } from '@tanstack/db'
619
620try {
621 collection.insert({
622 id: "1",
623 email: "not-an-email",
624 age: -5
625 })
626} catch (error) {
627 if (error instanceof SchemaValidationError) {
628 console.log(error.type) // 'insert' or 'update'
629 console.log(error.message) // "Validation failed with 2 issues"
630 console.log(error.issues) // Array of validation issues
631 }
632}
633```
634
635### Error Structure
636
637```typescript
638error.issues = [
639 {
640 path: ['email'],
641 message: 'Invalid email address'
642 },
643 {
644 path: ['age'],
645 message: 'Number must be greater than 0'
646 }
647]
648```
649
650### Displaying Errors in UI
651
652```typescript
653const handleSubmit = async (data: unknown) => {
654 try {
655 collection.insert(data)
656 } catch (error) {
657 if (error instanceof SchemaValidationError) {
658 // Show errors by field
659 error.issues.forEach(issue => {
660 const fieldName = issue.path?.join('.') || 'unknown'
661 showFieldError(fieldName, issue.message)
662 })
663 }
664 }
665}
666```
667
668### React Example
669
670```tsx
671import { SchemaValidationError } from '@tanstack/db'
672
673function TodoForm() {
674 const [errors, setErrors] = useState<Record<string, string>>({})
675
676 const handleSubmit = (e: React.FormEvent) => {
677 e.preventDefault()
678 setErrors({})
679
680 try {
681 todoCollection.insert({
682 id: crypto.randomUUID(),
683 text: e.currentTarget.text.value,
684 priority: parseInt(e.currentTarget.priority.value)
685 })
686 } catch (error) {
687 if (error instanceof SchemaValidationError) {
688 const newErrors: Record<string, string> = {}
689 error.issues.forEach(issue => {
690 const field = issue.path?.[0] || 'form'
691 newErrors[field] = issue.message
692 })
693 setErrors(newErrors)
694 }
695 }
696 }
697
698 return (
699 <form onSubmit={handleSubmit}>
700 <input name="text" />
701 {errors.text && <span className="error">{errors.text}</span>}
702
703 <input name="priority" type="number" />
704 {errors.priority && <span className="error">{errors.priority}</span>}
705
706 <button type="submit">Add Todo</button>
707 </form>
708 )
709}
710```
711
712---
713
714## Best Practices
715
716### Keep Transformations Simple
717
718> **Performance Note:** Schema validation is synchronous and runs on every optimistic mutation. For high-frequency updates, keep transformations simple.
719
720```typescript
721// ❌ Avoid expensive operations
722const schema = z.object({
723 data: z.string().transform(val => {
724 // Heavy computation on every mutation
725 return expensiveParsingOperation(val)
726 })
727})
728
729// ✅ Better: Validate only, process elsewhere
730const schema = z.object({
731 data: z.string() // Simple validation
732})
733
734// Process in component or mutation handler when needed
735const processedData = expensiveParsingOperation(todo.data)
736```
737
738### Use Union Types for Transformations (Essential)
739
740When 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.
741
742```typescript
743// ✅ REQUIRED: TInput accepts both string (new data) and Date (existing data)
744const schema = z.object({
745 created_at: z.union([z.string(), z.date()])
746 .transform(val => typeof val === 'string' ? new Date(val) : val)
747})
748// TInput: { created_at: string | Date }
749// TOutput: { created_at: Date }
750
751// ❌ WILL BREAK: Updates fail because draft contains Date but TInput only accepts string
752const schema = z.object({
753 created_at: z.string().transform(val => new Date(val))
754})
755// TInput: { created_at: string }
756// TOutput: { created_at: Date }
757// Problem: collection.update() passes a Date to a schema expecting string!
758```
759
760**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.
761
762### Validate at the Boundary
763
764Let the collection schema handle validation. Don't duplicate validation logic:
765
766```typescript
767// ❌ Avoid: Duplicate validation
768function addTodo(text: string) {
769 if (!text || text.length < 3) {
770 throw new Error("Text too short")
771 }
772 todoCollection.insert({ id: "1", text })
773}
774
775// ✅ Better: Let schema handle it
776const todoSchema = z.object({
777 id: z.string(),
778 text: z.string().min(3, "Text must be at least 3 characters")
779})
780```
781
782### Type Inference
783
784Let TypeScript infer types from your schema:
785
786```typescript
787const todoSchema = z.object({
788 id: z.string(),
789 text: z.string(),
790 completed: z.boolean()
791})
792
793type Todo = z.infer<typeof todoSchema> // Inferred type
794
795// ✅ Use the inferred type
796const collection = createCollection(
797 queryCollectionOptions({
798 schema: todoSchema,
799 // TypeScript knows the item type automatically
800 getKey: (item) => item.id // item is Todo
801 })
802)
803```
804
805### Custom Error Messages
806
807Provide helpful error messages for users:
808
809```typescript
810const userSchema = z.object({
811 username: z.string()
812 .min(3, "Username must be at least 3 characters")
813 .max(20, "Username is too long (max 20 characters)")
814 .regex(/^[a-zA-Z0-9_]+$/, "Username can only contain letters, numbers, and underscores"),
815 email: z.string().email("Please enter a valid email address"),
816 age: z.number()
817 .int("Age must be a whole number")
818 .min(13, "You must be at least 13 years old")
819})
820```
821
822---
823
824## Full-Context Examples
825
826### Example 1: Todo App with Rich Types
827
828A complete todo application demonstrating validation, transformations, and defaults:
829
830```typescript
831import { z } from 'zod'
832import { createCollection } from '@tanstack/react-db'
833import { not } from '@tanstack/db'
834import { queryCollectionOptions } from '@tanstack/query-db-collection'
835
836// Schema with validation, transformations, and defaults
837const todoSchema = z.object({
838 id: z.string(),
839 text: z.string().min(1, "Todo text cannot be empty"),
840 completed: z.boolean().default(false),
841 priority: z.enum(['low', 'medium', 'high']).default('medium'),
842 due_date: z.union([
843 z.string(),
844 z.date()
845 ]).transform(val => typeof val === 'string' ? new Date(val) : val).optional(),
846 created_at: z.union([
847 z.string(),
848 z.date()
849 ]).transform(val => typeof val === 'string' ? new Date(val) : val)
850 .default(() => new Date()),
851 tags: z.array(z.string()).default([])
852})
853
854type Todo = z.infer<typeof todoSchema>
855
856// Collection setup
857const todoCollection = createCollection(
858 queryCollectionOptions({
859 queryKey: ['todos'],
860 queryFn: async () => {
861 const response = await fetch('/api/todos')
862 const todos = await response.json()
863 // Reuse schema to parse and transform API responses
864 return todos.map((todo: any) => todoSchema.parse(todo))
865 },
866 getKey: (item) => item.id,
867 schema: todoSchema,
868 queryClient,
869
870 onInsert: async ({ transaction }) => {
871 const todo = transaction.mutations[0].modified
872
873 // Serialize dates for API
874 await fetch('/api/todos', {
875 method: 'POST',
876 headers: { 'Content-Type': 'application/json' },
877 body: JSON.stringify({
878 ...todo,
879 due_date: todo.due_date?.toISOString(),
880 created_at: todo.created_at.toISOString()
881 })
882 })
883 },
884
885 onUpdate: async ({ transaction }) => {
886 await Promise.all(
887 transaction.mutations.map(async (mutation) => {
888 const { original, changes } = mutation
889
890 // Serialize any date fields in changes
891 const serialized = {
892 ...changes,
893 due_date: changes.due_date instanceof Date
894 ? changes.due_date.toISOString()
895 : changes.due_date
896 }
897
898 await fetch(`/api/todos/${original.id}`, {
899 method: 'PATCH',
900 headers: { 'Content-Type': 'application/json' },
901 body: JSON.stringify(serialized)
902 })
903 })
904 )
905 },
906
907 onDelete: async ({ transaction }) => {
908 await Promise.all(
909 transaction.mutations.map(async (mutation) => {
910 await fetch(`/api/todos/${mutation.original.id}`, {
911 method: 'DELETE'
912 })
913 })
914 )
915 }
916 })
917)
918
919// Component usage
920function TodoApp() {
921 const { data: todos } = useLiveQuery(q =>
922 q.from({ todo: todoCollection })
923 .where(({ todo }) => not(todo.completed))
924 .orderBy(({ todo }) => todo.created_at, 'desc')
925 )
926
927 const [errors, setErrors] = useState<Record<string, string>>({})
928
929 const addTodo = (text: string, priority: 'low' | 'medium' | 'high') => {
930 try {
931 todoCollection.insert({
932 id: crypto.randomUUID(),
933 text,
934 priority,
935 due_date: "2024-12-31T23:59:59Z"
936 // completed, created_at, tags filled automatically by defaults
937 })
938 setErrors({})
939 } catch (error) {
940 if (error instanceof SchemaValidationError) {
941 const newErrors: Record<string, string> = {}
942 error.issues.forEach(issue => {
943 const field = issue.path?.[0] || 'form'
944 newErrors[field] = issue.message
945 })
946 setErrors(newErrors)
947 }
948 }
949 }
950
951 const toggleComplete = (todo: Todo) => {
952 todoCollection.update(todo.id, (draft) => {
953 draft.completed = !draft.completed
954 })
955 }
956
957 return (
958 <div>
959 <h1>Todos</h1>
960
961 {errors.text && <div className="error">{errors.text}</div>}
962
963 <button onClick={() => addTodo("Buy groceries", "high")}>
964 Add Todo
965 </button>
966
967 <ul>
968 {todos?.map(todo => (
969 <li key={todo.id}>
970 <input
971 type="checkbox"
972 checked={todo.completed}
973 onChange={() => toggleComplete(todo)}
974 />
975 <span>{todo.text}</span>
976 <span>Priority: {todo.priority}</span>
977 {todo.due_date && (
978 <span>Due: {todo.due_date.toLocaleDateString()}</span>
979 )}
980 <span>Created: {todo.created_at.toLocaleDateString()}</span>
981 </li>
982 ))}
983 </ul>
984 </div>
985 )
986}
987```
988
989### Example 2: E-commerce Product with Computed Fields
990
991```typescript
992import { z } from 'zod'
993
994// Schema with computed fields and transformations
995const productSchema = z.object({
996 id: z.string(),
997 name: z.string().min(3, "Product name must be at least 3 characters"),
998 description: z.string().max(500, "Description too long"),
999 base_price: z.number().positive("Price must be positive"),
1000 tax_rate: z.number().min(0).max(1).default(0.1),
1001 discount_percent: z.number().min(0).max(100).default(0),
1002 stock: z.number().int().min(0).default(0),
1003 category: z.enum(['electronics', 'clothing', 'food', 'other']),
1004 tags: z.array(z.string()).default([]),
1005 created_at: z.union([z.string(), z.date()])
1006 .transform(val => typeof val === 'string' ? new Date(val) : val)
1007 .default(() => new Date())
1008}).transform(data => ({
1009 ...data,
1010 // Computed fields
1011 final_price: data.base_price * (1 + data.tax_rate) * (1 - data.discount_percent / 100),
1012 in_stock: data.stock > 0,
1013 display_price: `$${(data.base_price * (1 + data.tax_rate) * (1 - data.discount_percent / 100)).toFixed(2)}`
1014}))
1015
1016type Product = z.infer<typeof productSchema>
1017
1018const productCollection = createCollection(
1019 queryCollectionOptions({
1020 queryKey: ['products'],
1021 queryFn: async () => api.products.getAll(),
1022 getKey: (item) => item.id,
1023 schema: productSchema,
1024 queryClient,
1025
1026 onInsert: async ({ transaction }) => {
1027 const product = transaction.mutations[0].modified
1028
1029 // API only needs base fields, not computed ones
1030 await api.products.create({
1031 name: product.name,
1032 description: product.description,
1033 base_price: product.base_price,
1034 tax_rate: product.tax_rate,
1035 discount_percent: product.discount_percent,
1036 stock: product.stock,
1037 category: product.category,
1038 tags: product.tags
1039 })
1040 }
1041 })
1042)
1043
1044// Usage
1045function ProductList() {
1046 const { data: products } = useLiveQuery(q =>
1047 q.from({ product: productCollection })
1048 .where(({ product }) => product.in_stock) // Use computed field
1049 .orderBy(({ product }) => product.final_price, 'asc')
1050 )
1051
1052 const addProduct = () => {
1053 productCollection.insert({
1054 id: crypto.randomUUID(),
1055 name: "Wireless Mouse",
1056 description: "Ergonomic wireless mouse",
1057 base_price: 29.99,
1058 discount_percent: 10,
1059 category: "electronics",
1060 stock: 50
1061 // tax_rate, tags, created_at filled by defaults
1062 // final_price, in_stock, display_price computed automatically
1063 })
1064 }
1065
1066 return (
1067 <div>
1068 {products?.map(product => (
1069 <div key={product.id}>
1070 <h3>{product.name}</h3>
1071 <p>{product.description}</p>
1072 <p>Price: {product.display_price}</p>
1073 <p>Stock: {product.in_stock ? `${product.stock} available` : 'Out of stock'}</p>
1074 <p>Category: {product.category}</p>
1075 </div>
1076 ))}
1077 </div>
1078 )
1079}
1080```
1081
1082---
1083
1084## For Integration Authors
1085
1086If 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.
1087
1088See 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.
1089
1090---
1091
1092## Related Topics
1093
1094- **[Mutations Guide](./mutations.md)** - Learn about optimistic mutations and how schemas validate mutation data
1095- **[Error Handling Guide](./error-handling.md)** - Comprehensive guide to handling `SchemaValidationError` and other errors
1096- **[Collection Options Creator Guide](./collection-options-creator.md)** - For integration authors: creating custom collection types with schema support
1097- **[StandardSchema Specification](https://standardschema.dev)** - Full specification for StandardSchema v1