initialValue Changed in Ant Design Form | ATLASSC.NET
Skip to main content
/// .DATA.FRAGMENT_20230413

initialValue Changed in Ant Design Form

2 minAuthor: Z.SHINCHVEN

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

RackNerd Billboard Banner
Share node:
/// .RELATED.DATA_STREAMSShared tags

Related posts

Scanning_database_for_correlations…

/// .UPLINK.SUBSCRIBE

Keep your deck synced with every new transmission from ATLASSC.NET. Subscribe over RSS or Atom, or wire the whole archive straight into your AI assistant with the MCP server.