Skip to content

Commit d6f1fda

Browse files
authored
feat: remove data slice when set as undefined
'lodash/fp/unset' is now used for property removals. This has the benefit of also removing the key of the property instead of only setting its value to undefined.
1 parent 9acbbab commit d6f1fda

File tree

2 files changed

+52
-5
lines changed

2 files changed

+52
-5
lines changed

packages/core/src/reducers/core.ts

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525

2626
import cloneDeep from 'lodash/cloneDeep';
2727
import setFp from 'lodash/fp/set';
28+
import unsetFp from 'lodash/fp/unset';
2829
import get from 'lodash/get';
2930
import filter from 'lodash/filter';
3031
import isEqual from 'lodash/isEqual';
@@ -285,11 +286,19 @@ export const coreReducer: Reducer<JsonFormsCore, CoreActions> = (
285286
} else {
286287
const oldData: any = get(state.data, action.path);
287288
const newData = action.updater(cloneDeep(oldData));
288-
const newState: any = setFp(
289-
action.path,
290-
newData,
291-
state.data === undefined ? {} : state.data
292-
);
289+
let newState: any;
290+
if (newData !== undefined) {
291+
newState = setFp(
292+
action.path,
293+
newData,
294+
state.data === undefined ? {} : state.data
295+
);
296+
} else {
297+
newState = unsetFp(
298+
action.path,
299+
state.data === undefined ? {} : state.data
300+
);
301+
}
293302
const errors = validate(state.validator, newState);
294303
return {
295304
...state,

packages/core/test/reducers/core.test.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -562,6 +562,44 @@ test('core reducer - update - should update errors', (t) => {
562562
});
563563
});
564564

565+
test('core reducer - update - setting a state slice as undefined should remove the slice', (t) => {
566+
const schema = {
567+
type: 'object',
568+
properties: {
569+
foo: {
570+
type: 'string',
571+
},
572+
fizz: {
573+
type: 'string',
574+
},
575+
},
576+
};
577+
578+
const before: JsonFormsCore = {
579+
data: {
580+
foo: 'bar',
581+
fizz: 42,
582+
},
583+
schema: schema,
584+
uischema: {
585+
type: 'Label',
586+
},
587+
errors: [],
588+
validator: new Ajv().compile(schema),
589+
};
590+
591+
const after = coreReducer(
592+
before,
593+
update('foo', (_) => {
594+
return undefined;
595+
})
596+
);
597+
598+
t.not(before, after);
599+
t.not(before.data, after.data);
600+
t.deepEqual(Object.keys(after.data), ['fizz']);
601+
});
602+
565603
test('core reducer - updateErrors - should update errors with empty list', (t) => {
566604
const before: JsonFormsCore = {
567605
data: {},

0 commit comments

Comments
 (0)