how to use ant design form initialValue

Viewed 32262

Which is right using antd Form initialValue?

I want to know that if antd form initialValue is using to set initial data or just to show value when the form doesn't have value.

const Component = ({ id }) => {
  const initialName = 'John'
  const { data } = useQuery(GET_NAME, { variables: { id } })
  if (data) { 
    initialName = data.name 
  }

  return (
  <Form.Item>
    {form.getFieldDecorator('name', { initialValue: initialName })(<Input />)}
   </Form.Item>
 )
}

const Component = ({ id }) => {
  const { data } = useQuery(GET_NAME, {
    variables: { id },
    onCompleted: res => { form.setFieldsValue({ name: res.data.name }) }
  })

  return (
  <Form.Item>
    {form.getFieldDecorator('name', { initialValue: 'John' })(<Input />)}
   </Form.Item>
 )
}
5 Answers

You should wrap your form items with the Form component and add the initial value to the Form instead of the Form.Item.

<Form
  initialValues={{ username:'default value' }}
  onFinish={onFinish}
  onFinishFailed={onFinishFailed}>
  <Form.Item
    label="Username"
    name="username"
    rules={[{ required: true, message: 'Please input your username!' }]}>
      <Input />
  </Form.Item>
</Form>

For me, setting the initialValues works if it an object that is already present when the form loads, let's sat it is "static". However, when that object is fetched async (using a useEffect hook), initialValues or even settings initialValue on the form's items, doesn't seem to work. Any thoughts?

Yeah, the doc is clear. I made a mistake. Instead of initialValue I used initialValues (plural) in getFieldDecorator.

Also, make sure if the version you are using is Ant 3.X initiate their values in getFieldDecorator or if you're using version 4.X use initialValues as an attribute of Form.

Using "setFieldsValue" inside useEffect works amazing!

useEffect(() => {
    props.form.setFieldsValue({
        someFormField: formCalculatedValue,
    });        
}, [someDependencies]);
Related