I have a form where i need to save the values as an array:
function App() {
const {
setValue,
register,
handleSubmit,
watch,
formState: { errors }
} = useForm();
const onSubmit = (data) => {
console.log(data, "submit");
}; // your form submit function which will invoke after successful validation
const allValues = watch("example") || [];
console.log(allValues);
return (
<form onSubmit={handleSubmit(onSubmit)}>
{[1, 2, 3].map((v, index) => {
return (
<input value={v} type="checkbox" {...register(`example[${index}]`)} />
);
})}
<input
onChange={(e) => {
setValue("example", e.target.value);
}}
/>
<input type="submit" />
</form>
);
}
Here: setValue("example", e.target.value); i want to set my text input value inside the result, so when i add check some checkboxes like 1 and 2 and also add test value in text input, when i will save i need to get the next result [1,2,'test']. If there is not a value in text input i should't add anything in the array.
question: How to solve the issue? Now if i add test in array i get [t,e,s,t].
demo: https://codesandbox.io/s/react-hook-form-get-started-forked-q2xhj5?file=/src/index.js:129-840