Skip to content

Commit

Permalink
fix: ensure correct error structure for array field with error that b…
Browse files Browse the repository at this point in the history
…ecomes empty (#3785)

* cleanup arrays if the last value, which is not undefined,
gets removed from it

(cherry picked from commit dcc63d9)

* chore: improve changeset

---------

Co-authored-by: Christoph Gruber <[email protected]>
  • Loading branch information
quantizor and Christoph Gruber authored May 26, 2023
1 parent 35fa4cc commit bc9cb28
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
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 @@ -306,7 +306,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 @@ -383,6 +383,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

1 comment on commit bc9cb28

@vercel
Copy link

@vercel vercel bot commented on bc9cb28 May 26, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

formik-docs – ./website

formik-docs-jared.vercel.app
formik.org
www.formik.org
formik-docs-git-master-jared.vercel.app
formik-docs.vercel.app

Please sign in to comment.