Skip to content

Commit 645478b

Browse files
🐞 fix FieldArray errors overriding nested fields (#13476)
* Initial plan * fix: preserve nested field array errors when root error and trigger coexist When a resolver returns mixed errors (both root-level and nested indexed errors) for a field array, calling trigger() alongside a field array action (like remove()) could cause nested field errors to be wiped out. Root cause: executeSchemaAndUpdateState() was calling updateFieldArrayRootError() for all plain-object field array errors. updateFieldArrayRootError() used convertToArrayPayload() to coerce the existing errors, but when those errors were already a plain object (set by the useFieldArray useEffect), this wrapped the entire plain object as index 0 of an array — causing all the correctly-indexed nested errors to become inaccessible. Fix 1 (createFormControl.ts): Only call updateFieldArrayRootError() for field array errors that are root-only plain objects (no numeric/index keys). When the error has numeric keys (mixed root + nested), set it directly so both root info (via .type/.message) and nested errors (via [i]) are preserved. Fix 2 (updateFieldArrayRootError.ts): Replace convertToArrayPayload() with an Array.isArray() check so that non-array existing errors are not wrapped. This prevents a scenario where a second trigger() with a root-only error wraps a previously-set plain object, losing its nested entries. * update lint --------- Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: bill <[email protected]>
1 parent 889c752 commit 645478b

3 files changed

Lines changed: 120 additions & 3 deletions

File tree

‎src/__tests__/useFieldArray.test.tsx‎

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -754,6 +754,121 @@ describe('useFieldArray', () => {
754754
).toBeInTheDocument();
755755
});
756756
});
757+
758+
it('should preserve nested field errors after remove when both root and field errors exist', async () => {
759+
type FormValues = {
760+
test: { value: string }[];
761+
};
762+
763+
const App = () => {
764+
const {
765+
register,
766+
control,
767+
trigger,
768+
formState: { errors },
769+
} = useForm<FormValues>({
770+
mode: 'onChange',
771+
resolver: async (data): Promise<ResolverResult<FormValues>> => {
772+
const fieldErrors: { test?: any } = {};
773+
if (data.test.length < 4) {
774+
fieldErrors.test = {
775+
type: 'min',
776+
message: 'Needs at least 4 items',
777+
};
778+
}
779+
for (const [index, item] of data.test.entries()) {
780+
if (item.value.length < 3) {
781+
fieldErrors.test = fieldErrors.test || [];
782+
fieldErrors.test[index] = {
783+
value: {
784+
type: 'minLength',
785+
message: `Item ${index} too short`,
786+
},
787+
};
788+
}
789+
}
790+
return Object.keys(fieldErrors).length
791+
? { values: {}, errors: fieldErrors }
792+
: { values: data, errors: {} };
793+
},
794+
defaultValues: {
795+
// Start with 3 items (min(4) fails) and item 2 has a short value
796+
test: [{ value: 'hello' }, { value: 'goodbye' }, { value: 'ab' }],
797+
},
798+
});
799+
const { fields, remove } = useFieldArray({ control, name: 'test' });
800+
801+
return (
802+
<form>
803+
{errors.test?.type && <p>Array error: {errors.test.message}</p>}
804+
{fields.map((item, i) => (
805+
<div key={item.id}>
806+
<input {...register(`test.${i}.value` as const)} />
807+
<button
808+
type="button"
809+
onClick={() => {
810+
remove(i);
811+
trigger('test');
812+
}}
813+
>
814+
remove {i}
815+
</button>
816+
{errors.test?.[i]?.value && (
817+
<span>
818+
Item {i} error: {errors.test[i]?.value?.message}
819+
</span>
820+
)}
821+
</div>
822+
))}
823+
<button type="button" onClick={() => trigger('test')}>
824+
validate
825+
</button>
826+
</form>
827+
);
828+
};
829+
830+
render(<App />);
831+
832+
// Trigger initial validation: 3 items, min(4) fails → root error
833+
// AND item 2 ('ab', 2 chars) has a field error
834+
await act(async () => {
835+
fireEvent.click(screen.getByRole('button', { name: 'validate' }));
836+
});
837+
838+
// Both root error and nested field error should be visible
839+
await waitFor(() =>
840+
expect(
841+
screen.queryByText('Array error: Needs at least 4 items'),
842+
).toBeInTheDocument(),
843+
);
844+
await waitFor(() =>
845+
expect(
846+
screen.queryByText('Item 2 error: Item 2 too short'),
847+
).toBeInTheDocument(),
848+
);
849+
850+
// Remove item 0 while root error type stays the same (still min(4) failing)
851+
// The errors are stored as a plain object at this point.
852+
// Removing item 0 ('hello') means 'ab' moves to index 1.
853+
// After remove + trigger: root error should still appear AND the field
854+
// error for the remaining short-value item (now at index 1) should appear.
855+
await act(async () => {
856+
fireEvent.click(screen.getByRole('button', { name: 'remove 0' }));
857+
});
858+
859+
await waitFor(() =>
860+
expect(
861+
screen.queryByText('Array error: Needs at least 4 items'),
862+
).toBeInTheDocument(),
863+
);
864+
865+
// 'ab' is now at index 1 - its field error should be shown
866+
await waitFor(() =>
867+
expect(
868+
screen.queryByText('Item 1 error: Item 1 too short'),
869+
).toBeInTheDocument(),
870+
);
871+
});
757872
});
758873

759874
describe('when component unMount', () => {

‎src/logic/createFormControl.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -545,7 +545,9 @@ export function createFormControl<
545545
for (const name of names) {
546546
const error = get(errors, name);
547547
error
548-
? _names.array.has(name) && isObject(error)
548+
? _names.array.has(name) &&
549+
isObject(error) &&
550+
!Object.keys(error).some((key) => !Number.isNaN(Number(key)))
549551
? updateFieldArrayRootError(
550552
_formState.errors,
551553
{ [name]: error } as Partial<Record<string, FieldError>>,

‎src/logic/updateFieldArrayRootError.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import type {
55
FieldValues,
66
InternalFieldName,
77
} from '../types';
8-
import convertToArrayPayload from '../utils/convertToArrayPayload';
98
import get from '../utils/get';
109
import set from '../utils/set';
1110

@@ -14,7 +13,8 @@ export default <T extends FieldValues = FieldValues>(
1413
error: Partial<Record<string, FieldError>>,
1514
name: InternalFieldName,
1615
): FieldErrors<T> => {
17-
const fieldArrayErrors = convertToArrayPayload(get(errors, name));
16+
const existingErrors = get(errors, name);
17+
const fieldArrayErrors = Array.isArray(existingErrors) ? existingErrors : [];
1818
set(fieldArrayErrors, ROOT_ERROR_TYPE, error[name]);
1919
set(errors, name, fieldArrayErrors);
2020
return errors;

0 commit comments

Comments
 (0)