antd onChange is firing three times with each key stroke

Viewed 1474

I have the following form in antd with code taken almost verbatim from the official website. Code sandbox is also here:

The problem with the below code is that on every key stroke in the field, the onChange method fires three (3) times. You can verify that in the codesandbox link as well if you open the browser console. I would like to understand why is that and what can be done about it.

import React from 'react';
import { Form, Input } from 'antd';

import {FieldData} from 'rc-field-form/es/interface.d.ts';
interface CustomizedFormProps {
  onChange: (fields: FieldData[]) => void;
  fields: FieldData[];
}


const CustomizedForm: React.FC<CustomizedFormProps> = ({ onChange, fields }) => {
  return (
    <Form
      name="global_state"
      layout="inline"
      fields={fields}
      onFieldsChange={(changedFields, allFields) => {
        onChange(allFields);
      }}
    >
      <Form.Item
        name="username"
        label="Username"
        rules={[{ required: true, message: 'Username is required!' }]}
      >
        <Input />
      </Form.Item>
    </Form>
  );
};

export class AntdFormTest extends React.Component<{}, {fields: FieldData[]}> {
  
  constructor(props: {}) {
    super(props);
    this.state = {fields: [{name: ['username'], value: 'Ant Design'}]};
  }

  render() {
    return (
      <>
        <CustomizedForm
          fields={this.state.fields}
          onChange={newFields => {
            console.log('onChange fired');
            this.setState({fields: newFields});
          }}
        />
        <pre className="language-bash">{JSON.stringify(this.state, null, 2)}</pre>
      </>
    );
  }
};
1 Answers

You should use the onValuesChange method instead. The onFieldsChange is fired when a field is updated(rerendered). See more here: https://ant.design/components/form/#API

Here it explains when you should use the OnFieldsChange method

Related