Skip to content

Commit

Permalink
Bugfix: updateInputsWithValue doesn't update nested field (#604)
Browse files Browse the repository at this point in the history
  • Loading branch information
rkuykendall authored Jan 22, 2021
1 parent 880ab7a commit e2fc916
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
31 changes: 31 additions & 0 deletions __tests__/Formsy.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -687,6 +687,37 @@ describe('value === false', () => {
expect(getWrapperInstance(inputs.at(1)).getValue()).toEqual(true);
});

it('should be able to set a deep value with updateInputsWithValue', () => {
class TestForm extends React.Component<{}, { valueBar: number; valueFoo: { valueBar: number }}> {
constructor(props) {
super(props);
this.state = {
valueFoo: { valueBar: 1 },
valueBar: 2,
};
}

render() {
return (
<Formsy>
<TestInput name="foo.bar" value={this.state.valueFoo.valueBar} />
<TestInput name="bar" value={this.state.valueBar} />
<button type="submit">Save</button>
</Formsy>
);
}
}

const form = mount(<TestForm />);
const inputs = form.find('Formsy(TestInput)');
const formsyForm = form.find(Formsy);
expect(getWrapperInstance(inputs.at(0)).getValue()).toEqual(1);
expect(getWrapperInstance(inputs.at(1)).getValue()).toEqual(2);
getFormInstance(formsyForm).updateInputsWithValue({ foo: { bar: 3 }, bar: 4 });
expect(getWrapperInstance(inputs.at(0)).getValue()).toEqual(3);
expect(getWrapperInstance(inputs.at(1)).getValue()).toEqual(4);
});

it('should be able to reset the form using custom data', () => {
class TestForm extends React.Component<{}, { value: number; valueDeep: number }> {
constructor(props) {
Expand Down
11 changes: 5 additions & 6 deletions src/Formsy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -408,12 +408,11 @@ export class Formsy extends React.Component<FormsyProps, FormsyState> {
};

// Set the value of components
public updateInputsWithValue: IUpdateInputsWithValue<any> = (values, validate) => {
Object.entries(values).forEach(([name, value]) => {
const input = this.inputs.find((component) => component.props.name === name);

if (input) {
input.setValue(value, validate);
public updateInputsWithValue: IUpdateInputsWithValue<any> = (data, validate) => {
this.inputs.forEach((component) => {
const { name } = component.props;
if (data && has(data, name)) {
component.setValue(get(data, name), validate);
}
});
};
Expand Down

0 comments on commit e2fc916

Please sign in to comment.