Search forms
Build a GET form that keeps search and filter conditions in the URL. The form and @k8ordo/state share one schema.
On this page
Sharing the schema
src/lib/list-state.tsexport const listState = definePageState('product-list', {
url: z.object({
q: z.string().default(''),
inStock: z.stringbool().default(false),
}),
});src/routes/products/page.tsxconst filterFields = formFields(listState.url);
export default function ProductsPage() {
return <Filters fields={filterFields} />;
}Describe URL state as the url schema of definePageState from @k8ordo/state. How to write that schema is covered in URL.
Pass that same schema to formFields.
In @k8ordo/framework’s server mode, a page that exports the same schema as search receives the validated conditions. See Parameters.
GET form
src/components/filters.tsxconst form = useForm(fields);
const [current] = useAppState(listState);
const q = form.field('q');
const inStock = form.field('inStock');
<form {...form.props} method="get">
<input {...q.input} defaultValue={current.q} type="search" />
<input {...inStock.input} defaultChecked={current.inStock} />
<button type="submit">Filter</button>
</form>There is no Server Action to receive the submission, so useForm takes fields alone. Without the second argument (the state an action returns), the form is still checked on submit. A condition that does not match the schema is never written to the URL.
Each field starts from the current value read with useAppState, passed as defaultValue or defaultChecked.
With @k8ordo/router, a GET submission to the same path becomes a state update. See How it works.
Note
defaultValue and defaultChecked only apply on the first render, so the back button changes the URL but not the fields. To make the fields follow the URL, rebuild the form whenever it changes, with <form key={search}>.
Filter demo
A GET form that rewrites this page’s actual URL.
- URL
No query (all defaults)- state
{ q: '', min: 0, inStock: false }
Try it
- Type a keyword and press “Filter”. The URL gains
?q=, and the page does not reload. - Check “In stock only” and submit. The URL gains
inStock=true. - Press the browser’s back button. The URL and the state values return to the previous conditions.
Checkbox that submits a string
A boolean in the URL is a z.stringbool(). Its checkbox submits the same string update() writes for true, so a submission produces the same URL as update().
@k8ordo/ui’s Checkbox does not pass the value in input to its <input>. Render this field as a plain <input>. See Forms.