Review

Hive inspection edit form resets defaults after load

Apiary techs open an existing hive inspection and the Save button stays disabled even after they change mite count, because defaultValues only applied on mount when the query was still empty. Wire reset(values) when the inspection query succeeds so RHF treats server data as the new defaults and dirtyFields/isDirty reflect real edits.

RHFTier 2react-hook-formresetdirtyFieldsasync

Click a line to flag it, pick one or more labels, then submit. If the change looks correct, approve it.

components/apiary/HiveInspectionForm.tsx+12-6
11import { useEffect } from "react";
22import { useForm } from "react-hook-form";
33import { useQuery } from "@tanstack/react-query";
44import { fetchHiveInspection, updateHiveInspection } from "@/api/apiary";
55
66type InspectionForm = {
77 broodPattern: string;
88 miteCount: number;
99 notes: string;
1010};
1111
1212export function HiveInspectionForm({ inspectionId }: { inspectionId: string }) {
1313 const { data, isSuccess } = useQuery({
1414 queryKey: ["hive-inspection", inspectionId],
1515 queryFn: () => fetchHiveInspection(inspectionId),
1616 });
1717
1818 const {
1919 register,
2020 handleSubmit,
21+ reset,
2122 formState: { dirtyFields, isDirty },
2223 } = useForm<InspectionForm>({
23- // data is undefined on first render — these stick as empty forever
24- defaultValues: {
25- broodPattern: data?.broodPattern ?? "",
26- miteCount: data?.miteCount ?? 0,
27- notes: data?.notes ?? "",
28- },
24+ defaultValues: { broodPattern: "", miteCount: 0, notes: "" },
2925 });
3026
27+ // Promote server payload to form defaults so dirtyFields tracks user edits only.
28+ useEffect(() => {
29+ if (!isSuccess || !data) return;
30+ reset({
31+ broodPattern: data.broodPattern,
32+ miteCount: data.miteCount,
33+ notes: data.notes,
34+ });
35+ }, [isSuccess, data, reset]);
36+
3137 return (
3238 <form onSubmit={handleSubmit((v) => updateHiveInspection(inspectionId, v))}>
3339 <input type="number" {...register("miteCount", { valueAsNumber: true })} />
3440 {dirtyFields.miteCount ? <span>unsaved mite count</span> : null}
3541 <button type="submit" disabled={!isDirty}>Save inspection</button>
3642 </form>
3743 );
3844}