@k8ordo/form

Async checks

Attach a check only the server can answer, such as whether a username is already taken, to one field. Its result shows where every other error does.

On this page

Adding a check

actions.ts
'use server';

export async function checkHandle(handle: string) {
  return (await handleExists(handle))
    ? 'This username is already taken'
    : undefined;
}
signup-form.tsx
const handle = form.field('handle');
const taken = useAsyncCheck(checkHandle, form.revalidate);

<input {...handle.input} {...taken.props} />
{handle.error !== undefined && <p>{handle.error}</p>}
<button disabled={taken.isChecking} type="submit">
  Sign up
</button>

Pass useAsyncCheck a function that takes the value and resolves to a message, or to undefined when the value is fine. A Server Action works as it is.

The second argument is the revalidate that useForm returns. Spread the returned props onto the field, next to input.

Showing the result

useAsyncCheck applies the result to the field with setCustomValidity and shows it through revalidate. It is treated like a built-in check, and the message is read from field()’s error.

isChecking is true while the check is running. Pass it to the submit button’s disabled so the form cannot be sent until the check finishes.

Check timing

It runs only when the field loses focus, not on every keystroke.

A few more rules apply.

  • Leaving the field with the value of the last result does not ask again.
  • When results arrive out of order, only the one for the newest value is used.
  • Emptying the field and leaving it clears the last result.
  • When the request itself fails, it applies no verdict either way, and the error is reported to the browser with reportError.
Information

Note

The result is only a hint while typing. Someone else may take the name before the form is sent, so check again in the Server Action.

Playground

Taken name demo

A demo that treats admin, k8o and ordo as taken and stands in for the server with a function in the browser.

Try it

  1. Type admin and leave the field. After a moment, “This username is already taken” shows.
  2. While it waits, “Checking” shows and the “Sign up” button cannot be pressed.
  3. Change it to another name and leave the field. The error goes away.
k8ordo

React libraries that use Baseline features without holding back.