Search code examples
reactjsreact-nativeantd

how to auto populate form fields using data from the server?


I created a form in React. When the user enters a value in the 'gage id' field, if that value exists in the database, the system should automatically populate other fields based on that input. How can I achieve this in React? hear is my code:

function WorkOrderRef() {
  const [form] = Form.useForm()
  const [id, setId] = useState()
const [gageInfo, setGageInfo] = useState()
const meta = {
    columns: 2,
    fields: [
      {
        key: "Id",
        label: "ID",
        placeholder: "",
        onChange: (e) => setId(e.target.value),
      },
      {
        key: "description",
        label: "Description",
        placeholder: "",
        //value: referenceData.name,
      },
      {
        key: "serial number",
        label: "Serial Number",
        placeholder: "",
      },
      {
        key: "due date",
        label: "Due Date",
        placeholder: "",
        widget: "date-picker",
      },
      {
        key: "colibration",
        label: "Colibration",
        widget: "select",
        options,
      },
    ],
  }
useEffect(() => {
    try {
      if (id) {
        console.log(id)
        fetch(`api/id=${id}`)
          .then((result) => result.json())
          .then((response) => setGageInfo(response))
      }
    } catch (e) {
      console.log(e)
    }
  }, [id])
return (
    <Fragment>
        <Form form={form} onFinish={handleFinish}>
          <FormBuilder meta={meta} form={form} />
          <Form.Item className="ant-form-item--btn">
            <Button type="primary" htmlType="submit">
              Add
            </Button>
          </Form.Item>
        </Form>
</Fragment>
  )
}

export default WorkOrderRef

In reality, I can fetch data related to the "gage id" from the server, but I'm finding it challenging to display that data in the form fields. How can I make this happen in React?


Solution

  • You should use `form.setFieldsValue. Take a look into this section of antd docs. As you can see in Button component, it's reseting all fields of the form but you can use this to assign data to your form too:

    <Button onClick={() => form.setFieldsValue({
      description: 'item description',
      'serial number': 'abc123'
      ...
    })} />;