URL
You will be able to write the url schema of a page state. A URL shows the same screen to whoever gets the link, but it carries only strings, and anyone can edit it.
On this page
Defaults
page: z.coerce.number().int().min(1).default(1),
sort: z.enum(['price', 'name']).optional(),Links made before a field existed still get opened, so a URL parameter can be missing. Every field takes .default() or .optional(). The error for a field that lacks one is described on Places.
A field with no sensible default takes .optional(), like sort above. When its parameter is absent, the value is undefined.
Parameter types
catalog-state.tsimport { definePageState } from '@k8ordo/state';
import * as z from 'zod';
export const catalogState = definePageState('catalog', {
url: z.object({
q: z.string().default(''),
page: z.coerce.number().int().min(1).default(1),
inStock: z.stringbool().default(false),
tags: z.array(z.enum(['sale', 'new'])).default([]),
}),
});Each field is written so that it parses its value from a string.
- Strings:
z.string(), orz.enum()for a fixed set of choices. - Numbers:
z.coerce.number(), which turns the"2"of?page=2into2. - Booleans:
z.stringbool(), which reads"true"astrueand writestrueas"true". - Arrays:
z.array(), written as the same parameter repeated (?tags=sale&tags=new), with[]as the default.
When the parameter of a field that is not an array is repeated, the first value is read. update() leaves parameters the schema does not declare untouched, so they can sit next to one like utm_source.
Refused schemas
inStock: z.boolean().default(false),
inStock: z.stringbool().default(false),update() writes the values into a query string and reads them back, so a field needs a spelling that reads the URL’s "false" back. z.boolean() does not accept "false", and z.coerce.boolean() reads it as true. Neither is allowed, as a field or as an array’s item: the module throws as it loads, with an error beginning url boolean fields must use z.stringbool().
tags: z.array(z.string()).optional(),
tags: z.array(z.string()).default([]),An array that is .optional() or defaults to anything but [] is refused too. An absent parameter and an empty array are the same URL, so with any other default an empty array could never be written. The error begins url array fields must default to [].
A value no URL can carry is refused the moment something writes it. Hand a z.date() field a Date, and update() or href throws. The error names the field and contains has no URL serialization.
Values the schema rejects
const read = (query: string) =>
catalogState.parseUrl(new URLSearchParams(query));
read('q=lamp&page=0');
// { q: 'lamp', page: 1, inStock: false, tags: [] }
read('page=abc&inStock=true');
// { q: '', page: 1, inStock: true, tags: [] }
read('tags=sale&tags=new');
// { q: '', page: 1, inStock: false, tags: ['sale', 'new'] }
read('tags=sale&tags=old');
// { q: '', page: 1, inStock: false, tags: [] }
read('q=red&q=blue');
// { q: 'red', page: 1, inStock: false, tags: [] }A value the schema rejects resets only that field to its default. The other fields keep what they read. Reading never throws.
An array counts as one field. A single rejected item resets the whole array to [].
price-state.tsexport const priceState = definePageState('price', {
url: z
.object({
min: z.coerce.number().min(0).default(0),
max: z.coerce.number().min(0).default(1000),
})
.refine((range) => range.min <= range.max),
});
priceState.parseUrl(new URLSearchParams('min=500&max=100'));
// { min: 0, max: 1000 }A .refine() on the whole schema checks the combination after each field has been read. When it rejects the combination, every field falls back to its default. If the refine does not accept the all-defaults value, the module throws as it loads, with an error beginning url schema rejects its own defaults.
Canonical URLs
catalogState.search({ page: 1, tags: ['sale'] });
// 'tags=sale'
catalogState.search({ tags: ['sale'], q: 'desk lamp' });
// 'q=desk+lamp&tags=sale'search and href leave out every field that sits at its default. The same state always gives the same, shortest URL. Links, bookmarks and cache keys that point at the same state agree.
Parameters follow the order the schema declares them in. A URL with a hand-written default such as ?page=1 reads to the same values as one without it. The next update() that changes a url value rewrites the query without that page=1.
Query reading demo
The query you type is read by parseUrl on the same definition as catalogState above, next to the query search writes back from it (this page’s own URL is left alone).
q'lamp'page2inStockfalsetags[]
- Rebuilt query
q=lamp&page=2
Try it
- Change
page=2topage=0. Onlypagefalls back to its default1, andqstays"lamp". - Add
&inStock=yesto the end.inStockbecomestrue, and the rebuilt query spells itinStock=true. - Add
&tags=sale&tags=newas well, andtagsreads as an array. Changenewtoold, a value outside the choices, and the whole oftagsgoes back to[].