# Persist

> Keep a draft in storage so a reload doesn't lose it.

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

A reload, a crash or a closed tab loses what the user typed. `persist()`
keeps a draft in storage and puts it back.

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

const forms = createForms({ fields: { TextField } });

const feedback = forms.define({
  defaultValues: { subject: "", message: "" },
  // Saves the value to localStorage under this key when the page is idle,
  // and restores it when the form mounts.
  plugins: [persist("feedback-draft")],
  onSubmit: (value) => value,
});

export default function FeedbackForm() {
  const form = useForm(feedback, { id: "feedback" });
  return (
    <form.Form>
      {(formProps) => (
        <form {...formProps}>
          <form.TextField name="subject" label="Subject" />
          <form.TextField name="message" label="Message" />
          {/* Reset writes the defaults, and `persist` saves those too. */}
          <button type="button" onClick={() => form.root.reset()}>
            Discard draft
          </button>
        </form>
      )}
    </form.Form>
  );
}
```

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

interface TextFieldProps {
  readonly field: FieldApi<string>;
  readonly label: string;
}

export function TextField({ field, label }: TextFieldProps) {
  return (
    <label>
      {label}
      <input {...inputProps(field)} />
    </label>
  );
}
```

Type something, then reload the page or press the demo's reset button.

`persist("feedback-draft")` saves the form value as JSON in `localStorage`
under that key, once the page is idle after a write. Pass other storage as
the second argument, as in `persist("feedback-draft", sessionStorage)`. Any
object with `getItem`, `setItem` and `removeItem` works.

## Restoring

The saved value is written back when the store first gets a listener, as when
a component mounts a field. The restore is a plugin write, not a user edit, so
its fields aren't marked edited and `history` makes no step from it.

The server never listens, so it never restores. The server render and the
render that hydrates show the defaults, and the draft shows in the render
after.

## Clearing the draft

A reset writes the defaults, and `persist` saves those too, so the draft is
gone after the next reload. To stop saving, leave `persist` out of the list.
`persist(key, undefined)` still means `localStorage`.

## When storage fails

Storage that throws, as when it is blocked or full, never breaks the form. A
failed save is dropped and the next write tries again. A saved value that
doesn't parse is removed, and the form starts from its defaults.
