DEV Community

ziadeh
ziadeh

Posted on

Autosave for React Hook Form

Developers frequently require the following when creating forms: - Automatic saving without a "Save" button - Debounced requests to prevent API overload.
Flexible mapping between form fields and API payloads; validation-aware saving that omits invalid data; and support for list fields (e.g., add/remove tags, sectors, categories)

RhfAutosave Logo

✨ Features

  • Debounced autosave — efficient API calls
  • Validation-aware — save only valid fields
  • 🔑 Key mapping — adapt form field names to API schema
  • 📊 Diff handling — handle add/remove operations for arrays
  • 🔗 tRPC transport helper included

📦 Installation

# With pnpm
pnpm add react-hook-form-autosave

# Or with npm
npm install react-hook-form-autosave

# Or with yarn
yarn add react-hook-form-autosave
Enter fullscreen mode Exit fullscreen mode

🖥️ Example

import { useForm } from "react-hook-form";
import { useRhfAutosave } from "react-hook-form-autosave";

const form = useForm({ defaultValues: { title: "" } });

const { isSaving } = useRhfAutosave({
  form,
  transport: async (payload) => {
    await fetch("/api/save", {
      method: "POST",
      body: JSON.stringify(payload),
    });
    return { ok: true };
  },
  debounceMs: 800,
});

return (
  <form>
    <input {...form.register("title")} placeholder="Title" />
    {isSaving && <span>Saving...</span>}
  </form>
);
Enter fullscreen mode Exit fullscreen mode

📚 Resources

Top comments (0)