avatar

ShīnChvën ✨

Effective Accelerationism

Powered by Druid

initialValue Changed in Ant Design Form

Thu Apr 13 2023

Problem

initialValue can take effect when the form is initialized, but it will not take effect when it is changed.

I'm building a form that can perform create and update operations. In create scenario, the initialValue is set before the form is rendered, it worked well. But in update scenario, the initialValue requires a network request to get the data, so it is set after the form is rendered. When it is set, the form has already been initialized, so the initialValue will not take effect.

Solution

I have tried several ways to solve this problem, such as setting keys to the component to force the form item to re-create. However, I have found a better solution, which is to use the setFieldsValue function of FormInstance to set the value of the form item.

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

const DemoForm = () => {

  const [form] = Form.useForm();

  useEffect(() => {
    // simulate a network request
    setTimeout(() => {
      form.setFieldsValue({
        name: 'value from network request',
      });
    }, 1000);
  }, []);

  return (
    <Form form={form}>
      <Form.Item name="name" initialValue="default value">
        <Input />
      </Form.Item>
    </Form>
  );
};

References