Skip to content

fix: field value updates may fail multiple times #754

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
5 changes: 3 additions & 2 deletions src/Field.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -606,6 +606,7 @@ class Field extends React.Component<InternalFieldProps, FieldState> implements F
this.dirty = true;

this.triggerMetaEvent();
const curValue = this.getValue();

let newValue: StoreValue;
if (getValueFromEvent) {
Expand All @@ -615,9 +616,9 @@ class Field extends React.Component<InternalFieldProps, FieldState> implements F
}

if (normalize) {
newValue = normalize(newValue, value, getFieldsValue(true));
newValue = normalize(newValue, curValue, getFieldsValue(true));
}
if (newValue !== value) {
if (newValue !== curValue) {
dispatch({
type: 'updateValue',
namePath,
Expand Down
35 changes: 34 additions & 1 deletion tests/field.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import Form, { Field } from '../src';
import type { FormInstance } from '../src';
import { act, fireEvent, render } from '@testing-library/react';
import { Input } from './common/InfoField';
import { getInput } from './common';
import timeout from './common/timeout';

describe('Form.Field', () => {
Expand Down Expand Up @@ -73,4 +72,38 @@ describe('Form.Field', () => {
onValuesChange.mockReset();
}
});

// https://github.com/react-component/field-form/issues/753
it('value change multiple times', async () => {
const form = React.createRef<FormInstance>();
const MockBtnInput = props => (
<>
<Input {...props} />
<button
onClick={() => {
props.onChange?.('');
props.onChange?.('A');
}}
>
change
</button>
</>
);
const { container } = render(
<Form ref={form}>
<Field name="input">
<MockBtnInput />
</Field>
</Form>,
);

// Trigger
for (let i = 0; i < 3; i += 1) {
fireEvent.click(container.querySelector('button'));
await act(async () => {
await timeout();
});
expect(form.current?.getFieldValue('input')).toBe('A');
}
});
});