Skip to content

Commit

Permalink
πŸ‘¨πŸ»β€πŸ’» fix #3296 - Log warning if conflicting keyName is used (#3299)
Browse files Browse the repository at this point in the history
* Log warning if conflicting keyName is used

* Update src/useFieldArray.ts

Co-authored-by: Bill <bluebill1049@hotmail.com>

Co-authored-by: Bill <bluebill1049@hotmail.com>
  • Loading branch information
milo- and bluebill1049 committed Oct 29, 2020
1 parent 30b580f commit 3eda58e
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
34 changes: 34 additions & 0 deletions src/useFieldArray.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,40 @@ describe('useFieldArray', () => {
expect(console.warn).not.toBeCalled();
});

it('should output error message when a conflicting fieldArray keyName is found in the fieldValues in development mode', () => {
jest.spyOn(console, 'warn').mockImplementation(() => {});

process.env.NODE_ENV = 'development';

renderHook(() => {
const { control } = useForm({
defaultValues: {
test: [{ id: '123' }],
},
});
useFieldArray({ control, name: 'test' });
});

expect(console.warn).toBeCalledTimes(1);
});

it('should not output error message when a conflicting fieldArray keyName is found in the fieldValues in production mode', () => {
jest.spyOn(console, 'warn').mockImplementation(() => {});

process.env.NODE_ENV = 'production';

renderHook(() => {
const { control } = useForm({
defaultValues: {
test: [{ id: '123' }],
},
});
useFieldArray({ control, name: 'test' });
});

expect(console.warn).toBeCalledTimes(0);
});

it('should throw custom error when control is not defined in development mode', () => {
process.env.NODE_ENV = 'development';

Expand Down
17 changes: 15 additions & 2 deletions src/useFieldArray.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,24 @@ const mapIds = <
>(
values: Partial<TFieldArrayValues>[] = [],
keyName: TKeyName,
): Partial<ArrayField<TFieldArrayValues, TKeyName>>[] =>
values.map((value: Partial<TFieldArrayValues>) => ({
): Partial<ArrayField<TFieldArrayValues, TKeyName>>[] => {
if (process.env.NODE_ENV !== 'production') {
for (const value of values) {
if (keyName in value) {
console.warn(
`πŸ“‹ useFieldArray fieldValues contain the keyName \`${keyName}\` which is reserved for use by useFieldArray. https://react-hook-form.com/api#useFieldArray`,
);

break;
}
}
}

return values.map((value: Partial<TFieldArrayValues>) => ({
[keyName]: generateId(),
...value,
}));
};

export const useFieldArray = <
TFieldArrayValues extends FieldValues = FieldValues,
Expand Down

0 comments on commit 3eda58e

Please sign in to comment.