Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Antd form setFieldValue on OnChange event is not working

I have a simple form field and I am trying to format and set the field value when onChange event is triggered using setFieldsValue which is not working.

I am trying to show the formatted value in the same text field.

Please find the sandbox link here codeSandbox

I dont want to create one more controlled component with state and set the value as I have 20 fields in the original form data. How could we set the form value on onChange itself.

like image 272
Rinsen S Avatar asked Sep 15 '25 16:09

Rinsen S


1 Answers

You are loosing the value being set because the onChange for Antd forms are async and are being run after the onChange that you have written. To get over this, you can simply add a setTimeout to the setFieldsValue:

onChange={e => {
  const value = e.target.value;
  const { setFieldsValue, getFieldValue } = this.props.form;
  setTimeout(() => {
    setFieldsValue({
      drivers: `+1 - ${value}`
    });
  }, 0);
}}

A more pragmatic way to do this, would be to use the normalize function of getFieldDecorator:

{getFieldDecorator(`drivers`, {
   initialValue: "",
   normalize: (value) => {
     return `+1 ${value}`;
   }
})}

However, this would add +1 on every change and that doesn't look like what you would want to do. So alternatively:

normalize: (value) => {
  if(!value.startsWith('+1')) {
    return `+1 ${value}`;
  } 
  return value;
}

Codesandbox

like image 107
Agney Avatar answered Sep 18 '25 05:09

Agney