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

[RFR] Support array of objects in sanitizeEmptyValues #4853

Merged
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
19 changes: 19 additions & 0 deletions packages/ra-core/src/form/sanitizeEmptyValues.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,25 @@ describe('sanitizeEmptyValues', () => {
sanitizeEmptyValues({ obj: { foo: null, foo2: 2 } }, { obj })
).toEqual({ obj: { foo: { bar: 1 }, foo2: null } });
});
it('should accept object values in arrays', () => {
const obj = [{ foo: 1 }, { foo: 2 }];
expect(sanitizeEmptyValues({ obj }, { obj: [{ foo: 1 }, {}] })).toEqual(
{ obj: [{ foo: 1 }, { foo: null }] }
);
expect(sanitizeEmptyValues({}, { obj })).toEqual({ obj });
});
it('should accept adding objects in arrays', () => {
const obj = [{ foo: 1, foo2: 2 }, { foo: 3 }, { foo: 4 }];
expect(
sanitizeEmptyValues({ obj: [{ foo: 1 }, { foo: 4 }] }, { obj })
).toEqual({ obj: [{ foo: 1, foo2: 2 }, { foo: 3 }, { foo: 4 }] });
});
it('should accept removing objects in array of objects', () => {
const obj = [{ foo: 1, foo2: 2 }, { foo: 3 }, { foo: 4 }];
expect(
sanitizeEmptyValues({ obj }, { obj: [{ foo: 1 }, { foo: 4 }] })
).toEqual({ obj: [{ foo: 1, foo2: null }, { foo: 4 }] });
});
it("should not ignore initial value when it's not of the same type", () => {
const initialValues = { a: 'foobar' };
const values = { a: { hello: 'world' } };
Expand Down
10 changes: 9 additions & 1 deletion packages/ra-core/src/form/sanitizeEmptyValues.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,16 @@ const sanitizeEmptyValues = (initialValues: object, values: object) => {
if (!initialValues) return values;
const initialValuesWithEmptyFields = Object.keys(initialValues).reduce(
(acc, key) => {
if (values[key] instanceof Date || Array.isArray(values[key])) {

Choose a reason for hiding this comment

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

What if values is null or undefined? is it possible? shouldn't there be an if for that?

if (values[key] instanceof Date) {
acc[key] = values[key];
} else if (Array.isArray(values[key])) {
if (Array.isArray(initialValues[key])) {
acc[key] = values[key].map((value, index) =>
sanitizeEmptyValues(initialValues[key][index], value)
);
} else {
acc[key] = values[key];
}
} else if (
typeof values[key] === 'object' &&
typeof initialValues[key] === 'object' &&
Expand Down