defaultValue or value not working on FormItem ANTD

Flezcano picture Flezcano · Nov 7, 2018 · Viewed 11.6k times · Source

I tried using the following code and the field never gets bind. The onChange property works well

const { getFieldDecorator, getFieldError, isFieldTouched } = this.props.form;
const NameError = isFieldTouched("Name") && getFieldError("Name");

<FormItem validateStatus={NameError ? "error" : ""} help={NameError || ""}>
  {getFieldDecorator("Name", {
    //initialValue: this.state.Data.Name,
    rules: [{ required: true, message: "Please input the component name!" }]
  })(
    <Input
      className="form-control"
      type="text"
      name="Name"
      defaultValue={this.state.Data.Name}
      onChange={this.onChange}
    />
  )}
</FormItem>

Am I missing something? I even used input instead of Input

EDIT On componentDidMount method I get the data from an API:

fetch('http://localhost:5728/Fields/get/' + this.state.Data.Id)
          .then(results=>{
            return results.json()
          })
          .then(data=>{

            this.setState({
                Data: {
                    Id: data.field.Id,
                    Name: data.field.Name,
                    Description: data.field.Description,
                    Value: data.field.Value
                }
              })

          })

I tried using initialValue, but it only works when the state value is set on the constructor method. When calling the API, the change is not reflected.

Answer

Alex picture Alex · Nov 7, 2018

The docs states that:

You cannot set value of form control via value defaultValue prop, and you should set default value with initialValue in getFieldDecorator instead.

You shouldn't call setState manually, please use this.props.form.setFieldsValue to change value programmatically.

So you just need to call setFieldsValue when the data is loaded from the backend:

fetch('http://localhost:5728/Fields/get/' + this.state.Data.Id)
      .then(results=>{
        return results.json()
      })
      .then(data=>{

        this.props.form.setFieldsValue({
                Id: data.field.Id,
                Name: data.field.Name,
                Description: data.field.Description,
                Value: data.field.Value
          })
      })

Or shorter, if data.field from backend totally matches the field names:

this.props.form.setFieldsValue(data.field)