1

I try to reset a nested array in react hook form without success I created the following sandbox sandbox

1
  • can you add a little more detail how you are trying to reset and how it is not working, also it would be helpful if you can add code in your question Commented Mar 23, 2021 at 5:38

1 Answer 1

2
+100

Your problem can be fixed by following the nested useFieldArray example here. That example is created by the library's author. I have no idea why it happens though, it may be a library bug or a quirk because the author never expects you to write code that way..

Basically you need to refactor your code by putting the nested fields in a child component instead of placing everything in one big component. So change this:

const { fields, remove } = useFieldArray({
  control,
  name: "names"
});

const { fields: nested } = useFieldArray({
  control,
  name: "names[0].nested"
});
<ul>
  {fields.map((item, index) => {
    return (
      <li key={item.id}>
        <input
          name={`names[${index}].firstName`}
          defaultValue={`${item.firstName}`}
          ref={register()}
        />
        <ul>
          {nested.map((nestedItem, nestedIndex) => {
            return (
              <li key={item.id}>
                <input
                  name={`names[${index}].nested[${nestedIndex}].lastName`}
                  defaultValue={`${nestedItem.lastName}`}
                  ref={register()}
                />
              </li>
            );
          })}
        </ul>
      </li>
    );
  })}
</ul>

To something like this:

Parent

const { fields, remove } = useFieldArray({
  control,
  name: "names"
});
<ul>
  {fields.map((item, index) => {
    return (
      <li key={item.id}>
        <input
          name={`names[${index}].firstName`}
          defaultValue={`${item.firstName}`}
          ref={register()}
        />
        <NestedArray
          index={index}
          control={control}
          register={register}
        />
      </li>
    );
  })}
</ul>

NestedArray

const { fields, remove } = useFieldArray({
  control,
  name: "names[0].nested"
});

return (
  <ul>
    {fields.map((nestedItem, nestedIndex) => {
      return (
        <li key={nestedItem.id}>
          <input
            name={`names[${index}].nested[${nestedIndex}].lastName`}
            defaultValue={`${nestedItem.lastName}`}
            ref={register()}
          />
        </li>
      );
    })}
  </ul>
);

Live Demo

Edit React Hook Form Reset useFieldArray (forked)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.