mimic
mimic

Reputation: 5224

how to pass the object into the ant.design form?

I'm loading data from the back-end dynamically. When it's done, it updates the state object:

componentDidMount = ()=>{

let response = await axios.get('/api/entity/' + id);
            if (response.data && response.data.result){
                this.setState({item: response.data.entity});
            } else {
                this.setState({status: 'error', message: response.data.error || constants.defaultErrorMessage})
            }
}

I also have a form in the same component. I can't figure out how to call setFieldsValue function to pass the data into the form.

<Form 
    onFinish={this.save}
    initialValues={this.state.entity}>
    {formItems}
    <Form.Item>
        <Button type="primary" htmlType="submit">
              Save data
        </Button>
    </Form.Item>
</Form>

Upvotes: 1

Views: 4613

Answers (1)

mimic
mimic

Reputation: 5224

It can be done with ref:

class Demo extends React.Component {
  formRef = React.createRef();

  componentDidMount() {
    this.formRef.current.setFieldsValue({
      username: 'Bamboo',
    });
  }

  render() {
    return (
      <Form ref={this.formRef}>
        <Form.Item name="username" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
      </Form>
    );
  }
}

Reference: https://ant.design/components/form/v3

Upvotes: 1

Related Questions