react-hook-form: Cannot remove a value from an index in a fields array

Hi!

I’m trying to remove a specific field in a fields array and I went through all the related issues but I couldn’t find the right solution. Whatever the index I try to remove, it always removes the last element, even with a setValue supposed to update the fields correctly.

Here is a sandbox that represents pretty much what I’m trying to do: https://codesandbox.io/s/react-hook-form-array-field-uncontrolled-input-yfeuw

I’ve tried with controlled inputs and it works but then the problem is that onChange is not firing the first time (I’ve tried with defaultValue instead of value and it doesn’t work either): https://codesandbox.io/s/react-hook-form-array-field-controlled-input-lswtl

I hope the sandboxes are clear enough. Let me know if you need more details!

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 18 (10 by maintainers)

Most upvoted comments

Just in case someone has the same problem, I think I know what I did wrong. I used the index of the map callback to set the key props of the fieldset like that :

      {indexes.map((index, key) => {
        const fieldName = `friends[${index}]`;
        return (
          <fieldset name={fieldName} key={key}>
             {...}
          </fieldset>
        );
      })}

This doesn’t work.

There’s one issue with this approach, which is that it removing an index will put an undefined entry in the array, at the removed index, when the values are returned in onSubmit or getValues.

Screen Shot 2019-10-23 at 12 32 44

FYI. Your codesandbox demo helped me a ton though, thanks @MinaAmrouche

@bluebill1049 I wasn’t sure to post here or there. But it seems someone opened an issue with yup already based off the comments. Thanks!

@johncalvinroberts do a filter(Boolean) should removes it

In fact, i will use your example to replace my codesandbox to help others.

I’m pretty sure I’ve already tried that but I must have done something wrong because it seems to work now 😄 I’ve created a new sandbox with this approach (added a counter to keep track of the indexes): https://codesandbox.io/s/react-hook-form-array-field-uncontrolled-input-t9fws

Thank you @bluebill1049 !

[{ index: 1 }, { index: 2 }, { index: 3}]

after remove…

[{ index: 1 }, { index: 3}]

should render the above index and item, instead array index