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