Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set API Data in react hook form

I have this input field. I am using this input to submit the data for adding new record on server. Now when user wants to edit the data I have to show the API data in this field. How to achieve this?

const {
  register,
  handleSubmit,
  formState: { errors },
} = useForm();

const onSubmit = handleSubmit((data) => {
  installNewPlugin(data);
});

 
<form onSubmit={onSubmit}>
  <TextInput
    label="Facebook Analytic Pixel id"
    name="id"
    register={register}
    rules={{ required: "This is a required field" }}
    error={errors?.id?.message}
  />
</form>
like image 683
Andaman Avatar asked Aug 13 '26 06:08

Andaman


1 Answers

You should use defaultValues prop for useForm. It can be both sync or async.

example:

// set default value sync
useForm({
  defaultValues: {
    firstName: 'Anda',
    lastName: 'Man'
  }
})

// set default value async
useForm({
  defaultValues: async () => fetch('/api-endpoint');
})

More Info here: https://react-hook-form.com/api/useform

like image 105
For fun programmer Avatar answered Aug 16 '26 01:08

For fun programmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!