import { useEffect, useRef } from "react"; import type { FieldValues, UseFormReturn } from "react-hook-form"; import { useI18n } from "@/i18n/i18n-context"; /** * Re-run validation on fields that already hold an error whenever the UI * locale changes, so their messages switch language too. * * react-hook-form caches each error's `message` string at validation time and * does NOT recompute it when the resolver identity changes. Without this, a * message produced in one locale stays in that locale until the field is * edited or the form is resubmitted. `trigger` re-validates in place using the * current (locale-aware) resolver and preserves the user's input — unlike * remounting via `key={locale}`, which resets fields to their defaultValues * and silently discards unsaved edits. */ export function useLocaleRevalidation( form: UseFormReturn, ): void { const { locale } = useI18n(); const initialLocale = useRef(locale); useEffect(() => { if (locale === initialLocale.current) return; initialLocale.current = locale; const erroredFields = Object.keys(form.formState.errors); if (erroredFields.length === 0) return; void form.trigger(erroredFields as Parameters[0]); // form is a stable RHF instance; depending only on locale keeps this to // "run once per locale change". // eslint-disable-next-line react-hooks/exhaustive-deps }, [locale]); }