diff --git a/packages/react-form-state/CHANGELOG.md b/packages/react-form-state/CHANGELOG.md index b7b710a850..edef71aa5e 100644 --- a/packages/react-form-state/CHANGELOG.md +++ b/packages/react-form-state/CHANGELOG.md @@ -6,6 +6,10 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). ## Unreleased +### Added + +- You can now use the onInitialValueChanged prop with fields having nested properties. + ### Fixed - `submit` now checks for the existence of `preventDefault` on the event passed in before calling it. diff --git a/packages/react-form-state/src/FormState.ts b/packages/react-form-state/src/FormState.ts index ef1923f971..25f188b6ff 100644 --- a/packages/react-form-state/src/FormState.ts +++ b/packages/react-form-state/src/FormState.ts @@ -395,7 +395,7 @@ function reconcileFormState( const fields: FieldStates = mapObject(values, (value, key) => { const oldField = oldFields[key]; - if (value === oldField.initialValue) { + if (isEqual(value, oldField.initialValue)) { return oldField; } diff --git a/packages/react-form-state/src/tests/FormState.test.tsx b/packages/react-form-state/src/tests/FormState.test.tsx index ca7499eea4..c09fecbbed 100644 --- a/packages/react-form-state/src/tests/FormState.test.tsx +++ b/packages/react-form-state/src/tests/FormState.test.tsx @@ -182,6 +182,64 @@ describe('', () => { }); }); + it('does not reset a field when initial value has not changed and deep comparison is required', () => { + const renderPropSpy = jest.fn(() => null); + const originalOption = 'color'; + const originalVariant1 = faker.commerce.color(); + const originalVariant2 = faker.commerce.color(); + const originalValues = { + variants: [ + { + option: originalOption, + values: [originalVariant1, originalVariant2], + }, + ], + }; + + const form = mount( + + {renderPropSpy} + , + ); + + const formDetails = lastCallArgs(renderPropSpy); + const changedVariants = [ + { + option: 'material', + values: [ + faker.commerce.productMaterial(), + faker.commerce.productMaterial(), + ], + }, + ]; + formDetails.fields.variants.onChange(changedVariants); + + const unchangedInitialVariants = [ + { + option: originalOption, + values: [originalVariant1, originalVariant2], + }, + ]; + + form.setProps({ + initialValues: { + variants: unchangedInitialVariants, + }, + }); + + const {fields} = lastCallArgs(renderPropSpy); + expect(fields).toMatchObject({ + variants: { + value: changedVariants, + initialValue: originalValues.variants, + dirty: true, + }, + }); + }); + it('does not reset errors when the initialValues prop is updated', async () => { const renderPropSpy = jest.fn(() => null); const originalValues = {