skip to Main Content

I have a simplified page where I am trying to set an object property token within the onSubmit function instead of within the form, but the setValue() function is not updating the property. What am I doing wrong?

type FormInputs = {
  firstName: string;
  lastName: string;
  token: string;
};

const App = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
    setValue
  } = useForm<FormInputs>();

  const onSubmit = (data: FormInputs) => {
    let tokenValue = "abc123xy" as string;
    setValue("token", tokenValue);
    alert(JSON.stringify(data));
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label>First Name</label>
      <input type="text" {...register("firstName")} />
      <label>Last Name</label>
      <input type="text" {...register("lastName")} />
      <input type="hidden" {...register("token")} />
      <button type="submit">Submit</button>
    </form>
  );
};

2

Answers


  1. register is for uncontrolled inputs. You can not change their value with setValue. You have to use useController or Controller

    https://react-hook-form.com/docs/usecontroller

    You are chaning the value of token, but there is nothing to make the rerender, so it won’t show the new value. This is why you have to use something to make that input controlled

    Login or Signup to reply.
  2. To update uncontrolled inputs you need to use Controller from react-hook library and here is the sample code. Also I dont recommend using let to define a variable instead use useState and then update its value.

    <Controller
                name="firstName"
                control={control}
                render={({ field }) => <input {...field} />}
     />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search