7

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>
 )
}
YOUNGHO KIM
  • 73
  • 1
  • 1
  • 3
  • For anyone reaching this question while searching for dynamic `initialValues`: Check [this](https://github.com/ant-design/ant-design/issues/22372#issuecomment-602102164). – therealak12 Sep 25 '21 at 19:02

5 Answers5

14

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>
Tomas Vancoillie
  • 3,463
  • 2
  • 29
  • 45
Hossein Mohammadi
  • 1,388
  • 11
  • 16
9

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?

aahoogendoorn
  • 444
  • 6
  • 9
  • 11
    Please post your questions as questions, not anwers! Anyway, I think [this](https://github.com/ant-design/ant-design/issues/22372#issuecomment-602102164) answers your question. You should call `setFieldValues` each time the initial values change. – therealak12 Sep 25 '21 at 19:00
3

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.

Noam Yizraeli
  • 4,446
  • 18
  • 35
Greko2015 GuFn
  • 512
  • 6
  • 13
2

Using "setFieldsValue" inside useEffect works amazing!

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

It will set the value to what you assign initialValue to, so the first approach is right

you can check it here https://ant.design/components/form/#API

Wijdan
  • 36
  • 4