@k8ordo/form

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.

ts
useForm(fields: FormFields, state?: FormState): UseFormReturn

Parameters

fieldsFormFields
The result of calling formFields in a Server Component, passed down as props.
stateFormState
The FormState the Server Action returned, which is the first value useActionState returns. 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 ref to spread onto the <form>. Do not put them on any other element.
field(path) => FieldView
Returns the FieldView for a path. A nested field is written with dots, as in user.email.
array(path) => ArrayView
Returns the ArrayView for 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.
isDirtyboolean
true once 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 onSubmit written after the spread replaces props.onSubmit. Call form.props.onSubmit(event) from your own handler.
  • noValidate is 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 state arrives, focus moves to the first failure in page order: a failed control, or the element showing formError or an array’s error, whichever comes first. States are told apart by their content and token, so a state built by hand needs a new token.
talk-form.tsx
const [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.

ts
type FieldView = {
  input: FieldInput;
  error: string | undefined;
  invalid: boolean;
  required: boolean;
};

Fields

inputFieldInput
The attributes to spread onto the control: name, type, required and the like. After a failed submission, the submitted value is in defaultValue.
errorstring | undefined
The error message to show now, from the browser’s check or from the server. undefined when there is none.
invalidboolean
true while there is an error. Pass it to aria-invalid and the like.
requiredboolean
true when 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 has value in its input: the string a checked box submits.

ArrayView

Import from @k8ordo/form

What form.array() returns for repeated rows.

ts
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 RowView each.
add() => void
Adds a row at the end.
canAddboolean
true while there are fewer rows than the schema’s .max().
canRemoveboolean
true while 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 id and tabIndex={-1} to spread onto the element that shows error, so focus can move to it after a failed submission.
order-form.tsx
const 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.

ts
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 FieldView for a key within the row. Its name has the form items[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.

ts
type FormErrorView = {
  message: string | undefined;
  props: { id: string; tabIndex: -1 };
};

Fields

messagestring | undefined
The text of state.formError, or undefined when there is none.
props{ id: string; tabIndex: -1 }
The id and tabIndex={-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.

ts
useAsyncCheck(
  check: (value: string) => Promise<string | undefined>,
  revalidate: UseFormReturn['revalidate'],
): AsyncCheck

Parameters

check(value: string) => Promise<string | undefined>
A function that takes the value and resolves to the message to show, or to undefined when the value is fine. A Server Action can be passed as it is.
revalidateUseFormReturn['revalidate']
The revalidate that useForm returns. 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 onBlur and ref to spread onto the control, next to field().input.
isCheckingboolean
true while a result is pending. Use it to disable the submit button.

Caveats

  • The returned message is applied with setCustomValidity, so it shows in the same error as 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.tsx
const 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.

ts
<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 input event on every change, so cross-field rules and isDirty react 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.

ts
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 when formFields runs.
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 what formFields returns, so you rarely write them.
  • It can be imported from either @k8ordo/form or @k8ordo/form/server.
k8ordo

React libraries that use Baseline features without holding back.