sanitizeDataForNewSchema removes discarded keys and leaves out objects the data doesn't hold
Detect
- In your code: calls to
sanitizeDataForNewSchema()orschemaUtils.sanitizeDataForNewSchema()whose result you read, spread over the old data, or assert in tests.
Form and its anyOf/oneOf switch already handle the new shape; see Form keeps or drops a value by comparing the field trees before and after a change.
Change
These placeholders it used to write are gone, at every level of the data:
- A key the old schema declares and the new one doesn't, or declares with another type that can't hold its value, is removed. Before, it was kept holding
undefined. - An object property the data doesn't hold, or holds as
nullwhere neither its type list nornullable: trueallowsnull, is left out. Before, it was written as{}wherever its schema declaresproperties, and anullwas kept where it declares none. - A key the new schema still declares but whose value it rejects, through its
const, itsenum, areadOnlydefaultor a prefix item the array can't hold, is removed, so the defaults fill it in. An array keeps the items past its prefix that its new items allow, and drops the rest. Before, the key was set toundefined, which kept the defaults from reaching it. - A key the data already holds as
undefinedkeeps it where the old schema declares the same type,const,enumor constant options,maxItemsanddefaultfor it, thedefaultthe object declares for it included. Otherwise it is removed too, unless a value replaces it, as a top-level clear is whenanyOf/oneOfoptions are switched.
With old = { type: 'object', properties: { x: { type: 'object', properties: { p: { type: 'string' } } } } }, newSchema the same with q in place of p, and the data { x: { p: 'v' } }:
-{ x: { p: undefined } }
+{ x: {} }
With newSchema = { type: 'object', properties: { k: { type: 'string' }, opt: { type: 'object', properties: { x: { type: 'string' } } } } } and the data { k: 'a' }:
-{ k: 'a', opt: {} }
+{ k: 'a' }
If you spread the result over the old data to clear what it discarded, the spread no longer clears those keys. Use the result on its own:
-const next = { ...oldData, ...schemaUtils.sanitizeDataForNewSchema(newSchema, oldSchema, oldData) };
+const next = schemaUtils.sanitizeDataForNewSchema(newSchema, oldSchema, oldData);
If you need the objects for a schema's optional object properties, fill them in with getDefaultFormState(), as a mount does.
Verify
- In tests that assert the result, the expected value has no
undefinedkeys or{}placeholders.toEqual()already treats a key holdingundefinedas absent, but it doesn't ignore a{}. - Keys the new schema discards are gone from the data you build from the result.
Also read: