Setting field value using setFieldValue Ant design

Viewed 5145

I am working with react and using Ant Design v4.1.0.
I have a form and on submit (onFinish), I send the id to reducer to get all the values of the fields. I am doing so because of my requirement (I've to select the id on the form itself and get all data many times also open same form from many place with specific id). There might be better ways to achieve my requirement but for now I'm doing so.

I am getting the desired data - props (I verified) but I'm not able to update fields with new props.

I have set

class CustomForm extends React.Component {
  formRef = React.createRef();
  constructor()
    render(){
      return(
        <Form 
          ref={this.formRef} 
          onFinish={this.onFinish} 
          name="customForm"
          initialValues=
           {{
             //(trying) email: this.props.customerData.map((d) => d.email)
           }}
        >
          <Form.Item label="Email" name="email">
            <Input />
          </Form.Item>
        </Form>
      )} 
}

I read ant design document and it is mentioned initialvalues does not work on state change and we should use setFieldsValue.

When trying I added "formRef" for class based form as per their example but not able to use setFieldValue.
I tried with

componentDidUpdate(){
    alert(JSON.stringify(this.props.customerData.map((d) => d.email)));
    this.formRef.current.setFieldsValue({
      mobileNumber: this.props.customerData
        .map((d) => d.mobile_number),
      email: this.props.customerData.map((d) => d.email),
    });
   }

and getting error Cannot read property 'setFieldsValue' of null

How can I set values, actually use setFieldValues?
And why this.formRef is null?

1 Answers

So on onFinish i set loading = true and my return was

(this.state.loading ? <Spin /> : <Form />)

The reason i was getting this.formRef = null.

Now solved the issue.

Thanks

Related