Skip to content

Commit

Permalink
Remove compaction to ensure consistent ordering of errors (#656)
Browse files Browse the repository at this point in the history
  • Loading branch information
SangJunBak authored Dec 30, 2023
1 parent 6f1b139 commit 235bbcd
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 7 deletions.
51 changes: 51 additions & 0 deletions src/__tests__/toNestErrors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,3 +204,54 @@ test('transforms flat object to nested object with root error for field array',
],
});
});

test('ensures consistent ordering when a field array has a root error and an error in the non-first element', () => {
const result = toNestErrors(
{
'fieldArrayWithRootError.1.name': {
type: 'second',
message: 'second message',
},
fieldArrayWithRootError: { type: 'root-error', message: 'root message' },
},
{
fields: {
fieldArrayWithRootError: {
name: 'fieldArrayWithRootError',
ref: { name: 'fieldArrayWithRootError' },
},
'fieldArrayWithRootError.0.name': {
name: 'fieldArrayWithRootError.0.name',
ref: { name: 'fieldArrayWithRootError.0.name' },
},
'fieldArrayWithRootError.1.name': {
name: 'fieldArrayWithRootError.1.name',
ref: { name: 'fieldArrayWithRootError.1.name' },
},
},
names: [
'fieldArrayWithRootError',
'fieldArrayWithRootError.0.name',
'fieldArrayWithRootError.1.name',
],
shouldUseNativeValidation: false,
},
);

expect(result).toEqual({
fieldArrayWithRootError: {
'1': {
name: {
type: 'second',
message: 'second message',
ref: { name: 'fieldArrayWithRootError.1.name' },
},
},
root: {
type: 'root-error',
message: 'root message',
ref: { name: 'fieldArrayWithRootError' },
},
},
});
});
8 changes: 1 addition & 7 deletions src/toNestErrors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,7 @@ export const toNestErrors = <TFieldValues extends FieldValues>(
});

if (isNameInFieldArray(options.names || Object.keys(errors), path)) {
const fieldArrayErrors = Object.assign(
{},
compact(get(fieldErrors, path)),
);
const fieldArrayErrors = Object.assign({}, get(fieldErrors, path));

set(fieldArrayErrors, 'root', error);
set(fieldErrors, path, fieldArrayErrors);
Expand All @@ -38,9 +35,6 @@ export const toNestErrors = <TFieldValues extends FieldValues>(
return fieldErrors;
};

const compact = <TValue>(value: TValue[]) =>
Array.isArray(value) ? value.filter(Boolean) : [];

const isNameInFieldArray = (
names: InternalFieldName[],
name: InternalFieldName,
Expand Down

0 comments on commit 235bbcd

Please sign in to comment.