Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: ensure correct error structure for array field with error that becomes empty #3785

Merged
merged 2 commits into from
May 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/fair-students-fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'formik': patch
---

Fixed field error state for array fields that have an error and become empty through an API like `arrayHelpers.remove`.

The prior behavior resolved the field error to `[undefined]`, now it is simply `undefined`.
7 changes: 6 additions & 1 deletion packages/formik/src/FieldArray.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,12 @@ class FieldArrayInner<Values = {}> extends React.Component<
if (isFunction(copy.splice)) {
copy.splice(index, 1);
}
return copy;
// if the array only includes undefined values we have to return an empty array
return isFunction(copy.every)
? copy.every(v => v === undefined)
? []
: copy
: copy;
},
true,
true
Expand Down
8 changes: 8 additions & 0 deletions packages/formik/test/FieldArray.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,14 @@ describe('<FieldArray />', () => {
expect(formikBag.errors.friends).toEqual(undefined);
expect(formikBag.touched.friends).toEqual(undefined);
});
it('should clean up errors', () => {
act(() => {
formikBag.setFieldError('friends.1', 'Field error');
arrayHelpers.remove(1);
});

expect(formikBag.errors.friends).toEqual(undefined);
});
});

describe('given array-like object representing errors', () => {
Expand Down