How to set API Data in react hook form

3.1k Views Asked by At

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>
1

There are 1 best solutions below

1
For fun programmer On

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