Skip to content

Commit 235bbcd

Browse files
authored
Remove compaction to ensure consistent ordering of errors (#656)
1 parent 6f1b139 commit 235bbcd

File tree

2 files changed

+52
-7
lines changed

2 files changed

+52
-7
lines changed

src/__tests__/toNestErrors.ts

+51
Original file line numberDiff line numberDiff line change
@@ -204,3 +204,54 @@ test('transforms flat object to nested object with root error for field array',
204204
],
205205
});
206206
});
207+
208+
test('ensures consistent ordering when a field array has a root error and an error in the non-first element', () => {
209+
const result = toNestErrors(
210+
{
211+
'fieldArrayWithRootError.1.name': {
212+
type: 'second',
213+
message: 'second message',
214+
},
215+
fieldArrayWithRootError: { type: 'root-error', message: 'root message' },
216+
},
217+
{
218+
fields: {
219+
fieldArrayWithRootError: {
220+
name: 'fieldArrayWithRootError',
221+
ref: { name: 'fieldArrayWithRootError' },
222+
},
223+
'fieldArrayWithRootError.0.name': {
224+
name: 'fieldArrayWithRootError.0.name',
225+
ref: { name: 'fieldArrayWithRootError.0.name' },
226+
},
227+
'fieldArrayWithRootError.1.name': {
228+
name: 'fieldArrayWithRootError.1.name',
229+
ref: { name: 'fieldArrayWithRootError.1.name' },
230+
},
231+
},
232+
names: [
233+
'fieldArrayWithRootError',
234+
'fieldArrayWithRootError.0.name',
235+
'fieldArrayWithRootError.1.name',
236+
],
237+
shouldUseNativeValidation: false,
238+
},
239+
);
240+
241+
expect(result).toEqual({
242+
fieldArrayWithRootError: {
243+
'1': {
244+
name: {
245+
type: 'second',
246+
message: 'second message',
247+
ref: { name: 'fieldArrayWithRootError.1.name' },
248+
},
249+
},
250+
root: {
251+
type: 'root-error',
252+
message: 'root message',
253+
ref: { name: 'fieldArrayWithRootError' },
254+
},
255+
},
256+
});
257+
});

src/toNestErrors.ts

+1-7
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,7 @@ export const toNestErrors = <TFieldValues extends FieldValues>(
2323
});
2424

2525
if (isNameInFieldArray(options.names || Object.keys(errors), path)) {
26-
const fieldArrayErrors = Object.assign(
27-
{},
28-
compact(get(fieldErrors, path)),
29-
);
26+
const fieldArrayErrors = Object.assign({}, get(fieldErrors, path));
3027

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

41-
const compact = <TValue>(value: TValue[]) =>
42-
Array.isArray(value) ? value.filter(Boolean) : [];
43-
4438
const isNameInFieldArray = (
4539
names: InternalFieldName[],
4640
name: InternalFieldName,

0 commit comments

Comments
 (0)