3

I have FirstName and LastName input Fields. I have a read only field called FullName which will have value based on FirstName and LastName. What ever is typed in the first name and last name input fields the Fullname will be Firstname + LastName. I am trying with below code however when i type the second field the first field value becomes undefined and full name ends up being undefined Smith

const F_Name = watch("FirstName", false);
const L_Name = watch("LastName", false);

<input id="edit-FirstName" type="text"   {...register('FirstName',{ required: "Enter Your FirstName"} })} onChange={(ev)=> setValue("FullName", ev.target.value + " " + L_Name )}  />

<input id="edit-LastName" type="text"   {...register('LastName',{ required: "Enter Your LastName"} })} onChange={(ev)=> setValue("FullName", F_Name + " " + ev.target.value  )}  />

<input readOnly id="edit-FullName" type="text"   {...register('FullName',{ required: "Enter Your FirstName and Last Name"} })}  />
Joy
  • 105
  • 1
  • 2
  • 10
  • Why are you using ```react-hook-form``` as opposed to normal ```inputs```? – Omar Apr 07 '22 at 10:29
  • It is already being used. I just posted them main portion of the code. – Joy Apr 07 '22 at 10:57
  • Instead of onChange, have you tried using an effect that sets the value? Something like this: `useEffect(() => { setValue('FullName', \`${F_Name} ${L_Name}\`); }, [F_Name, L_Name]);` Also, why are you passing in "false" as the default value in the watch calls? Have you tried removing that? – Ricardo Apr 11 '22 at 11:43

1 Answers1

1

You can use a combination of useWatch and useFormContext for that type of thing.

  1. Watch for changes of FirstName and LastName
const firstName = useWatch('FirstName');
const lastName = useWatch('LastName');
  1. Get setValue from formContext to update desired field
const { setValue } = useFormContext();
  1. Ensure you don't end up with undefined for FullName if any of the names is empty and concatenate them with space.
const fullName = [firstName, lastName].filter(name => name).join(' ');
  1. Update your FullName field
setValue('FullName', fullName);
Kuker
  • 65
  • 3
  • 11