React hook form, setValue, reset doesnt affect input #121
-
React hook form, setValue, reset doesnt affect input. Although I can see that the value in the react hook form has changed, but it doesn't show up on the field |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
@Denys357, can you please share a minimal React component with the React Hook Form and setValue included in it? |
Beta Was this translation helpful? Give feedback.
-
Okay... Now, I see where the problem comes from. The issue is that the import React from "react";
import { useForm, Controller } from "react-hook-form";
import FormItem from "antd/lib/form/FormItem";
import Form from "antd/lib/form";
import PhoneInput from "antd-phone-input";
type FormValues = {
phone: string;
};
export default function App() {
const [form] = Form.useForm();
const { control, handleSubmit, setValue } = useForm<FormValues>({
defaultValues: {
phone: "",
},
});
const onSubmit = (data: FormValues) => {
console.log("Submitted:", data);
};
const handleClick = () => {
setValue("phone", "+122343");
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label>Phone</label>
<Controller
name="phone"
control={control}
render={({ field }) => {
form.setFieldValue(field.name, field.value);
return (
<Form form={form}>
<FormItem name={field.name} noStyle>
<PhoneInput
{...field}
value={field.value}
onChange={(val) => field.onChange(val)}
/>
</FormItem>
</Form>
);
}}
/>
<button onClick={handleClick} style={{ marginTop: 12 }}>
Submit
</button>
</form>
);
} |
Beta Was this translation helpful? Give feedback.
Okay... Now, I see where the problem comes from. The issue is that the
value
is considered an initial value (I cannot remember why, but it had a reason to do so), and it is only changed using a Form context of the Ant Design. So, when using React Form Hooks, please wrap the Antd Phone Input with the Antd Form as represented in the following example: