@contract-kit/react-hook-form
v0.1.1
Published
React Hook Form integration for contract-kit with Standard Schema support
Maintainers
Readme
@contract-kit/react-hook-form
React Hook Form integration for Contract Kit
This package provides automatic form validation using your contract's body schema. Works with any Standard Schema library (Zod, Valibot, ArkType, etc.).
Installation
npm install @contract-kit/react-hook-form @contract-kit/core react-hook-form @hookform/resolvers reactTypeScript Requirements
This package requires TypeScript 5.0 or higher for proper type inference.
Usage
Basic Form
import { rhf } from "@contract-kit/react-hook-form";
import { createTodo } from "@/contracts/todos";
function CreateTodoForm() {
const { useForm } = rhf(createTodo);
const form = useForm({
defaultValues: {
title: "",
completed: false,
},
});
const onSubmit = form.handleSubmit((values) => {
// values is typed as: { title: string; completed?: boolean }
console.log("Creating todo:", values);
});
return (
<form onSubmit={onSubmit}>
<input
{...form.register("title")}
placeholder="What needs to be done?"
/>
{form.formState.errors.title && (
<p className="error">{form.formState.errors.title.message}</p>
)}
<label>
<input type="checkbox" {...form.register("completed")} />
Completed
</label>
<button type="submit" disabled={form.formState.isSubmitting}>
Create Todo
</button>
</form>
);
}With React Query Mutation
import { rhf } from "@contract-kit/react-hook-form";
import { rq } from "@/lib/rq";
import { createTodo } from "@/contracts/todos";
function CreateTodoForm() {
const { useForm } = rhf(createTodo);
const form = useForm({
defaultValues: { title: "" },
});
const mutation = rq(createTodo).useMutation({
onSuccessInvalidate: true,
});
const onSubmit = form.handleSubmit((values) => {
mutation.mutate({ body: values });
});
return (
<form onSubmit={onSubmit}>
<input {...form.register("title")} placeholder="Title" />
{form.formState.errors.title && (
<p>{form.formState.errors.title.message}</p>
)}
<button type="submit" disabled={mutation.isPending}>
{mutation.isPending ? "Creating..." : "Create"}
</button>
{mutation.isError && (
<p className="error">{mutation.error.message}</p>
)}
</form>
);
}Disabling Validation
If you need to disable the schema resolver (e.g., for partial form handling):
const { useForm } = rhf(createTodo);
const form = useForm({
resolverEnabled: false, // Disable schema validation
defaultValues: { title: "" },
});Using Contract Config Directly
You can pass either a contract builder or its config:
import { rhf } from "@contract-kit/react-hook-form";
import { createTodo } from "@/contracts/todos";
// Using ContractBuilder directly
const { useForm } = rhf(createTodo);
// Or using the contract config
const { useForm } = rhf(createTodo.config);API Reference
rhf(contract)
Creates a React Hook Form adapter for a contract.
const adapter = rhf(createTodo);adapter.useForm(props?)
Returns a React Hook Form useForm result with the contract's body schema as resolver.
const form = adapter.useForm({
defaultValues?: { ... },
resolverEnabled?: boolean, // default: true
// ...other React Hook Form options
});Type Inference
Form values are automatically typed based on the contract's body schema:
// Contract definition
const createTodo = todos
.post("/api/todos")
.body(z.object({
title: z.string().min(1),
description: z.string().optional(),
completed: z.boolean().optional(),
}))
.response(201, TodoSchema);
// Form values are inferred
const form = rhf(createTodo).useForm();
form.register("title"); // ✓ Valid
form.register("description"); // ✓ Valid
form.register("invalid"); // ✗ Type errorStandard Schema Support
This package uses the @hookform/resolvers/standard-schema resolver, which works with any Standard Schema compatible library:
- Zod -
z.object({ ... }) - Valibot -
v.object({ ... }) - ArkType -
type({ ... })
Validation Behavior
The resolver validates:
- On blur - When a field loses focus
- On change - After first submission attempt
- On submit - Before calling your submit handler
Validation errors are available via form.formState.errors:
{form.formState.errors.title && (
<span className="error">
{form.formState.errors.title.message}
</span>
)}Complete Example
import { rhf } from "@contract-kit/react-hook-form";
import { rq } from "@/lib/rq";
import { updateProfile } from "@/contracts/profile";
function ProfileForm({ profile }) {
const { useForm } = rhf(updateProfile);
const form = useForm({
defaultValues: {
name: profile.name,
email: profile.email,
bio: profile.bio ?? "",
},
});
const mutation = rq(updateProfile).useMutation({
onSuccess: () => {
toast.success("Profile updated!");
},
});
const onSubmit = form.handleSubmit((values) => {
mutation.mutate({ body: values });
});
const { errors, isDirty, isSubmitting } = form.formState;
return (
<form onSubmit={onSubmit}>
<div>
<label htmlFor="name">Name</label>
<input id="name" {...form.register("name")} />
{errors.name && <span className="error">{errors.name.message}</span>}
</div>
<div>
<label htmlFor="email">Email</label>
<input id="email" type="email" {...form.register("email")} />
{errors.email && <span className="error">{errors.email.message}</span>}
</div>
<div>
<label htmlFor="bio">Bio</label>
<textarea id="bio" {...form.register("bio")} />
{errors.bio && <span className="error">{errors.bio.message}</span>}
</div>
<button type="submit" disabled={!isDirty || isSubmitting}>
{isSubmitting ? "Saving..." : "Save Changes"}
</button>
</form>
);
}Related Packages
@contract-kit/core- Core contract definitions@contract-kit/react-query- TanStack Query integration@contract-kit/client- HTTP client
License
MIT
