react-hook-form / react-hook-form

📋 React Hooks for form state management and validation (Web + React Native)
https://react-hook-form.com
MIT License
41.1k stars 2.05k forks source link

[Bug]: useFieldArray append and remove resets field IDs #6233

Closed frw closed 3 years ago

frw commented 3 years ago

Version Number

7.13.0-next.3

Codesandbox/Expo snack

https://codesandbox.io/s/admiring-euclid-fimes?file=/src/App.js

Steps to reproduce

  1. Go to the code sandbox
  2. Make note of the field ID of the first element in the FieldArray
  3. Click on 'Append' to add a new element to the FieldArray
  4. Observe that the field ID of the first element is different from before
  5. Click on 'Remove' to remove the last element
  6. Observe again that the field ID of the first element changes again

Expected behaviour

In 7.12.2, the field IDs remain unchanged when appending and removing elements, and this is the expected behavior to prevent any unnecessary re-renders.

What browsers are you seeing the problem on?

No response

Relevant log output

No response

Code of Conduct

frw commented 3 years ago

Thanks @bluebill1049 for investigating and sending out a fix so quickly. When I try using 7.13.0-next.4 in the code sandbox above, it seems that removing items will still cause field IDs to change. Is this expected behavior?

bluebill1049 commented 3 years ago

thanks, missed the remove api.

bkincart commented 2 years ago

Is anyone still running into this? I'm on 7.18.1 and still encountering an error where removing an fields in my field array results in the id being removed completely from all other fields 😞

bluebill1049 commented 2 years ago

if id is a field, change keyName to others.

bluebill1049 commented 2 years ago

the next version 7.23.0

https://github.com/react-hook-form/react-hook-form/releases/tag/v7.23.0-next.0 https://github.com/react-hook-form/react-hook-form/releases/tag/v7.23.0-next.1

const App = () => {
  const { control, register, handleSubmit } = useForm<FormValues>({
    defaultValues: {
      test: [{id: 'UUID5678', test: 'data' }] // id will be remained as it match default keyName
    }
  });
  const { fields, append } = useFieldArray({
    control,
    name: 'test',
  });

  return (
    <form>
      {fields.map((field, index) => {
        return <input key={field.id} {...register(`test.${index}.test`)} />;
      })}

      <button
        type={'button'}
        onClick={() => {
          append({
            id: 'UUID1234', // id value will be remained as it match default keyName
            test: '1234',
          });
        }}
      >
        append
      </button>
      <button>submit</button>
    </form>
  );
};

will no longer remove id from user's data.

bkincart commented 2 years ago

Fantastic -- this looks like a great update, and your original comment did help me out after a little more debugging. Thanks so much, Bill!