use ref instead

This commit is contained in:
Josh Hawkins 2025-11-04 08:41:43 -06:00
parent 126cc5a23e
commit 107ed4174c

View File

@ -8,7 +8,7 @@ import {
FormMessage, FormMessage,
} from "@/components/ui/form"; } from "@/components/ui/form";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { useState, useEffect } from "react"; import { useState, useEffect, useRef } from "react";
import { useFormContext } from "react-hook-form"; import { useFormContext } from "react-hook-form";
import { generateFixedHash, isValidId } from "@/utils/stringUtil"; import { generateFixedHash, isValidId } from "@/utils/stringUtil";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
@ -41,13 +41,9 @@ export default function NameAndIdFields<T extends FieldValues = FieldValues>({
placeholderId, placeholderId,
}: NameAndIdFieldsProps<T>) { }: NameAndIdFieldsProps<T>) {
const { t } = useTranslation(["common"]); const { t } = useTranslation(["common"]);
const { const { watch, setValue, trigger, formState } = useFormContext<T>();
watch,
setValue,
trigger,
formState: { errors },
} = useFormContext<T>();
const [isIdVisible, setIsIdVisible] = useState(false); const [isIdVisible, setIsIdVisible] = useState(false);
const hasUserTypedRef = useRef(false);
const defaultProcessId = (name: string) => { const defaultProcessId = (name: string) => {
const normalized = name.replace(/\s+/g, "_").toLowerCase(); const normalized = name.replace(/\s+/g, "_").toLowerCase();
@ -63,33 +59,22 @@ export default function NameAndIdFields<T extends FieldValues = FieldValues>({
useEffect(() => { useEffect(() => {
const subscription = watch((value, { name }) => { const subscription = watch((value, { name }) => {
if (name === nameField) { if (name === nameField) {
hasUserTypedRef.current = true;
const processedId = effectiveProcessId(value[nameField] || ""); const processedId = effectiveProcessId(value[nameField] || "");
setValue(idField, processedId as PathValue<T, Path<T>>, { setValue(idField, processedId as PathValue<T, Path<T>>);
shouldValidate: false, trigger(idField);
});
// Only trigger validation if nameField has no errors
if (!errors[nameField]) {
trigger(idField);
}
} }
}); });
return () => subscription.unsubscribe(); return () => subscription.unsubscribe();
}, [ }, [watch, setValue, trigger, nameField, idField, effectiveProcessId]);
watch,
setValue,
trigger,
nameField,
idField,
effectiveProcessId,
errors,
]);
const idError = errors[idField]; // Auto-expand if there's an error on the ID field after user has typed
useEffect(() => { useEffect(() => {
if (idError) { const idError = formState.errors[idField];
if (idError && hasUserTypedRef.current && !isIdVisible) {
setIsIdVisible(true); setIsIdVisible(true);
} }
}, [idError]); }, [formState.errors, idField, isIdVisible]);
return ( return (
<> <>