@k8ordo/form

Editing

Build a form that edits a saved record, with the current values filled in. Read whether anything changed from isDirty, and revert with a reset.

On this page

Passing the current values

edit-talk-form.tsx
const title = form.field('title');
const isPublic = form.field('public');

<input defaultValue={talk.title} {...title.input} />
<input defaultChecked={talk.public} {...isPublic.input} />

Pass the current values as defaultValue, or defaultChecked for a checkbox. The fields are uncontrolled, so there is no value or onChange to wire up.

Write defaultValue before spreading input. After a failed submission, input carries the submitted value as defaultValue and overrides the current value written before it. Otherwise input has no defaultValue, so the field shows the current value.

Warning

Pitfall

Written after the spread, defaultValue replaces the submitted value with the current one, so a failed submission wipes out what was typed.

Detecting changes

edit-talk-form.tsx
useEffect(() => {
  if (!form.isDirty) return;
  const confirm = (event: BeforeUnloadEvent) => {
    event.preventDefault();
  };
  addEventListener('beforeunload', confirm);
  return () => {
    removeEventListener('beforeunload', confirm);
  };
}, [form.isDirty]);

The code above asks for confirmation before leaving the page with unsaved changes.

form.isDirty is true once any field differs from the value it was rendered with. Adding or removing a row counts as a change too.

useForm compares each field in the DOM with the default it was rendered with (defaultValue or defaultChecked). Typing does not re-render; only a change of isDirty does.

Warning

Pitfall

Avoid disabling the submit button with disabled={!form.isDirty}. In the server-rendered HTML isDirty is false, so the button cannot be pressed until JavaScript loads. After a failed submission isDirty is false again, so the same values cannot be resubmitted without an edit.

Reset

tsx
<button type="reset">Revert</button>

A type="reset" button makes the browser put every field back to its defaultValue. useForm detects the reset, clears the errors it was showing, and sets isDirty back to false.

After a Server Action, React resets the form the same way. After a failed submission, with defaultValue written before input, the reset keeps what was typed.

Playground

Edit form demo

A form that edits a saved talk, with the current values passed as defaultValue.

StateNo changes

Try it

  1. Edit the title. The badge changes to “Changed”.
  2. Type the original title back. The badge returns to “No changes”.
  3. Uncheck “Public”, then press “Revert”. Both the values and the badge go back.
k8ordo

React libraries that use Baseline features without holding back.