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

schemas.md

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