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
register
is for uncontrolled inputs. You can not change their value withsetValue
. You have to useuseController
orController
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 controlledTo update uncontrolled inputs you need to use
Controller
from react-hook library and here is the sample code. Also I dont recommend usinglet
to define a variable instead use useState and then update its value.