Client API
The hooks, components and types of @k8ordo/form used in Client Components. The functions called on the server are on the Server API page.
On this page
useForm
Import from @k8ordo/form
Connects the fields formFields derived to a <form> and the controls inside it.
useForm(fields: FormFields, state?: FormState): UseFormReturnParameters
fieldsFormFields- The result of calling
formFieldsin a Server Component, passed down as props. stateFormState- The
FormStatethe Server Action returned, which is the first valueuseActionStatereturns. Leave it out for a GET form that has no action.
Returns
UseFormReturn — The props to spread onto the <form>, and the functions that return what each control shows.
Fields
props{ onSubmit, onBlur, onInput, onReset, ref }- The event handlers and
refto spread onto the<form>. Do not put them on any other element. field(path) => FieldView- Returns the
FieldViewfor a path. A nested field is written with dots, as inuser.email. array(path) => ArrayView- Returns the
ArrayViewfor the path of an array of repeated rows. formErrorFormErrorView- The error that belongs to no field, with the props for the element that shows it.
isDirtybooleantrueonce any control differs from the value it was rendered with. Adding or removing a row counts too.revalidate(control) => void- Reads a control’s validity again and shows its message, as leaving the control does. Pass it to
useAsyncCheck.
Caveats
- Typed values are read from the DOM and never copied into React state, so typing does not re-render.
- An
onSubmitwritten after the spread replacesprops.onSubmit. Callform.props.onSubmit(event)from your own handler. noValidateis set from JavaScript on mount and is not in the HTML the server returns. Until JavaScript loads, the browser validates the input itself.- When a new
statearrives, focus moves to the first failure in page order: a failed control, or the element showingformErroror an array’s error, whichever comes first. States are told apart by their content andtoken, so a state built by hand needs a newtoken.
talk-form.tsxconst [state, formAction] = useActionState(createTalk, {});
const form = useForm(fields, state);
const title = form.field('title');
<form {...form.props} action={formAction}>
<input {...title.input} />
{title.error !== undefined && <p>{title.error}</p>}
</form>For the whole flow, see Get Started. For how errors are shown, see Errors.
FieldView
Import from @k8ordo/form
What form.field() returns for one control.
type FieldView = {
input: FieldInput;
error: string | undefined;
invalid: boolean;
required: boolean;
};Fields
inputFieldInput- The attributes to spread onto the control:
name,type,requiredand the like. After a failed submission, the submitted value is indefaultValue. errorstring | undefined- The error message to show now, from the browser’s check or from the server.
undefinedwhen there is none. invalidbooleantruewhile there is anerror. Pass it toaria-invalidand the like.requiredbooleantruewhen the schema rejects an empty submission. Use it for the label’s required marker.
Caveats
- A server error stays until the control is edited. An error from the browser’s check takes precedence over it.
- Only a
z.stringbool()field hasvaluein itsinput: the string a checked box submits.
ArrayView
Import from @k8ordo/form
What form.array() returns for repeated rows.
type ArrayView = {
rows: RowView[];
add: () => void;
canAdd: boolean;
canRemove: boolean;
error: string | undefined;
errorProps: { id: string; tabIndex: -1 };
};Fields
rowsRowView[]- The rows on screen, one
RowVieweach. add() => void- Adds a row at the end.
canAddbooleantruewhile there are fewer rows than the schema’s.max().canRemovebooleantruewhile there are more rows than the schema’s.min().errorstring | undefined- The error about the array itself, such as too many or too few rows. No row’s control shows it.
errorProps{ id: string; tabIndex: -1 }- The
idandtabIndex={-1}to spread onto the element that showserror, so focus can move to it after a failed submission.
order-form.tsxconst items = form.array('items');
{items.rows.map((row) => (
<div key={row.key}>
<input {...row.field('name').input} />
{items.canRemove && (
<button onClick={row.remove} type="button">
Remove
</button>
)}
</div>
))}
{items.canAdd && (
<button onClick={items.add} type="button">
Add a row
</button>
)}RowView
Import from @k8ordo/form
One repeated row.
type RowView = {
key: string;
index: number;
field: (itemKey?: string) => FieldView;
remove: () => void;
};Fields
keystring- The row’s identity, for
key. Removing a row does not change the other rows’ keys. indexnumber- The row’s current position, counted from 0.
field(itemKey?: string) => FieldView- Returns the
FieldViewfor a key within the row. Itsnamehas the formitems[0].name. For an array of scalars, call it with no argument. remove() => void- Removes this row.
Caveats
- Unlike a path, a key within a row is not checked by the types. A typo fails when the row renders, with the error
[@k8ordo/form] 配列 'items' に 'nmae' がありません。.
FormErrorView
Import from @k8ordo/form
The type of form.formError: an error that belongs to no field, such as one from a .refine() on the whole schema.
type FormErrorView = {
message: string | undefined;
props: { id: string; tabIndex: -1 };
};Fields
messagestring | undefined- The text of
state.formError, orundefinedwhen there is none. props{ id: string; tabIndex: -1 }- The
idandtabIndex={-1}to spread onto the element that shows the message, so focus can move to it after a failed submission.
useAsyncCheck
Import from @k8ordo/form
Asks the server about a control’s value when the person leaves it. Use it for a check only the server can answer, such as whether a name is already taken.
useAsyncCheck(
check: (value: string) => Promise<string | undefined>,
revalidate: UseFormReturn['revalidate'],
): AsyncCheckParameters
check(value: string) => Promise<string | undefined>- A function that takes the value and resolves to the message to show, or to
undefinedwhen the value is fine. A Server Action can be passed as it is. revalidateUseFormReturn['revalidate']- The
revalidatethatuseFormreturns. Once the result is in, it shows the control’s message through it.
Returns
AsyncCheck — The props to spread onto the control, and whether a check is in progress.
Fields
props{ onBlur, ref }- The
onBlurandrefto spread onto the control, next tofield().input. isCheckingbooleantruewhile a result is pending. Use it to disable the submit button.
Caveats
- The returned message is applied with
setCustomValidity, so it shows in the sameerroras every other message. - When results arrive out of order, only the result for the latest value is used. Leaving the control with the value of the last result does not ask again.
- Emptying the control and leaving it clears the last result. When the function rejects, nothing is applied, and the server checks the submission. What it rejected with is reported to the browser with
reportError.
slug-field.tsxconst slug = form.field('slug');
const taken = useAsyncCheck(checkSlugAvailable, form.revalidate);
<input {...slug.input} {...taken.props} />
<button disabled={taken.isChecking} type="submit">Save</button>HiddenValue
Import from @k8ordo/form
Includes the value of a component that renders no <input name>, such as a rich text editor, in the form’s submission.
<HiddenValue name={string} value={string} />Parameters
namestring- The name to submit under. Use the field’s path in the schema.
valuestring- The value to submit: the component’s state, as it is.
Caveats
- It fires an
inputevent on every change, so cross-field rules andisDirtyreact to it like a keystroke. - A reset does not restore the value. It is the caller’s state, so reset that too.
post-form.tsx<Editor onChange={setBody} value={body} />
<HiddenValue name="body" value={body} />FormFields
Import from @k8ordo/form
The type of what formFields returns and useForm takes. It is plain JSON, so a Server Component can pass it as props.
type FormFields<FieldPath, ArrayPath, StringCheckboxPath> = {
fields: Record<FieldPath, DerivedField>;
arrays: Record<ArrayPath, DerivedArray>;
rules: DerivedRule[];
dropped: DroppedCheck[];
};Fields
fieldsRecord<FieldPath, DerivedField>- Each field by path, with the control’s attributes and a message per check.
arraysRecord<ArrayPath, DerivedArray>- Each array of rows by path, with its row bounds and the fields of one row.
rulesDerivedRule[]- The cross-field rules declared with
defineForm. Their messages are fixed whenformFieldsruns. droppedDroppedCheck[]- The checks no HTML attribute can express, which the browser skips. The server still runs them.
Caveats
- It has three type arguments: the field paths, the array paths and the
z.stringbool()field paths. They are inferred from whatformFieldsreturns, so you rarely write them. - It can be imported from either
@k8ordo/formor@k8ordo/form/server.