# Dirty

> Know which fields the user changed, and get clean again after a save.

Source: https://forms.lunarhue.dev/react/plugins/dirty

Which fields did the user change? A Save button that stays disabled until
something changed, a "you have unsaved changes" prompt and a PATCH that sends
only the changed fields all need that answer. `dirty()` gives it. Change a
field, then change it back.

```tsx title="profile.tsx"
import { createForms, useForm } from "@lunarhue/forms-react";
import { baselineOnSubmit, dirty } from "@lunarhue/forms-react/plugins";
import { TextField } from "./TextField";

const forms = createForms({ plugins: [dirty()], fields: { TextField } });

const profile = forms.define({
  defaultValues: { name: "Ada Lovelace", email: "ada@example.com" },
  // A successful save makes the saved value the new baseline.
  plugins: [baselineOnSubmit()],
  onSubmit: (value) => value,
});

export default function ProfileForm() {
  const form = useForm(profile, { id: "profile" });
  return (
    <form.Form>
      {(formProps) => (
        <form {...formProps}>
          <form.TextField name="name" label="Name" />
          <form.TextField name="email" label="Email" />
          <form.State select={(state) => state.dirty}>
            {(changed) => (
              <div>
                <button type="submit" disabled={!changed}>
                  Save
                </button>
                <button
                  type="button"
                  disabled={!changed}
                  onClick={() => form.root.reset()}
                >
                  Discard
                </button>
              </div>
            )}
          </form.State>
        </form>
      )}
    </form.Form>
  );
}
```

```tsx title="TextField.tsx"
import { type FieldApi, type FormError, inputProps } from "@lunarhue/forms-react";

interface TextFieldProps {
  readonly field: FieldApi<string, FormError, "dirty">;
  readonly label: string;
}

// `field.dirty` is true while the value differs from its baseline. The
// "dirty" in the type says the form must have `dirty()`.
export function TextField({ field, label }: TextFieldProps) {
  return (
    <label>
      <span>
        {label}
        {field.dirty ? " (changed)" : null}
      </span>
      <input {...inputProps(field)} />
    </label>
  );
}
```

With `dirty()` installed, each field and the form get `dirty`, true while the
value differs from its baseline. The baseline starts as the form's starting
value. Typing a field back to that value makes it clean again.

```tsx
import { dirty } from "@lunarhue/forms-react/plugins";

const forms = createForms({ plugins: [dirty()] });
```

`form.store.changes()` lists the fields that differ, for event handlers and effects. An `equals` function on
`createForms` or a definition decides what counts as equal, as two dates with
the same time.

## Without it

Reading `dirty` on a form or field snapshot, calling `changes()` and giving
`equals` are type errors. The snapshots still carry `dirty: false` at runtime.
In development `changes()` throws
[`dirty:missing`](https://forms.lunarhue.dev/errors.md#core:dirty:missing). In production it returns an
empty list.

A component that reads `dirty` from a field it is given says so in its type.
See [Components that need a plugin](https://forms.lunarhue.dev/react/plugin-composition/components.md).

Core keeps the baseline either way, so a reset still goes back to it, and
`rebase` and `bind` still move it. [`rebase`](https://forms.lunarhue.dev/react/plugins/rebase.md) then compares values
by `Object.is` alone.

## Clean after a save

Nothing moves the baseline when a save succeeds. A settings page that stays on
screen after saving stays dirty, and its Save button never disables again.
`baselineOnSubmit` fixes that. Import it from the same entry and put it on the
definition:

```tsx
import { baselineOnSubmit, dirty } from "@lunarhue/forms-react/plugins";

const forms = createForms({ plugins: [dirty()] });
const settings = forms.define({
  defaultValues,
  plugins: [baselineOnSubmit()],
  onSubmit: saveSettings,
});
```

When a submit ends `"succeeded"`, the value `onSubmit` got as `ctx.input`
becomes the baseline. An invalid, refused or failed submit leaves the baseline
alone, and so does a submit that a reset stops.

- A field the user edits while the save runs keeps the newer text and stays
  dirty. Typing the saved text back makes it clean.
- Array items pair by the keys they had when the value was sent. An item
  inserted, removed or moved during the save keeps its own dirty flag.
- Moving the baseline writes no value, so `history` records no step.
- Without `dirty()` nothing is dirty, but the baseline still moves, so a later
  reset goes back to the saved value.

You don't need it for a create form that navigates away after saving, for a
search form, or for an app that refetches after saving and calls `rebase`
with the fresh copy.

The plugin trusts the value that was sent. When the server stores something
else, such as a trimmed name or a new `updatedAt`, bring its copy in with
[`rebase`](https://forms.lunarhue.dev/react/plugins/rebase.md).
