camelpard
camelpard

Reputation: 375

How to display defaultValues with useFieldArray hook in controlled components in react-hook-forms

I would like to have a field array that can be generated by the user by adding an infinite number of key/value pairs of input text fields. After submitting the form the fields should be saved and when coming back to the form the submitted field array should be displayed and have the same functionality. Meaning the user should be again able to add new key/value pairs of input text field or to delete them.

The form has separate components and one of them uses React Hook Form's useFieldArray hook. The input components are controlled components.

I made a simple app on codesandbox.

At first if you click on the add button everything looks fine. Fields get added and submitted.

But I can't figure out how to display the fieldset prop values passed to the ArrayFields component, see index.js:30

<ArrayFields
  fieldset={[
    { envName: "foo1", envRole: "bar1" },
    { envName: "foo2", envRole: "bar2" }
  ]}
/>

I tried setting defaultValues with the useForm hook, but it didn't work.

I'm a newbee to react and of course react hook form. If I understand react hook form right then anyway it's better to rely on the useFormContext hook and use the fields from the useFieldArray hook, see ArrayFields.js:6.

In ArrayFields.js:24-26 I tried to copy over the props in order to merge the fields with the fieldset.

const allFields = [...fields];                  // This does not display the passed prop values, alias fieldset
// const allFields = [...fieldset];             // This displays the passed prop values but adding field no longer works.
// const allFields = [...fieldset, ...fields];  // This results in weird add button adding multiple fields at once.

So what could I do here? Thanks a lot for your comments.


codesandbox

The app is based on

Upvotes: 14

Views: 28623

Answers (1)

Shariq
Shariq

Reputation: 316

Instead of passing default values to ArrayFields component just set default values in useForm hook like this.

const methods = useForm({
    defaultValues: {
      email: "[email protected]",
      firstName: "John",
      lastName: "Smith",
      systemRole: "Admin",
      envRoles: [
        { envName: "foo1", envRole: "bar1" },
        { envName: "foo2", envRole: "bar2" }
      ]
    }
  });

Check this codesandbox. I updated your code.

Upvotes: 21

Related Questions