score:-1

I defined a state variable for maintaining the gstNo that will be fetched from the API based on the state id selected from the drop-down. Like this:

 this.state = {
   gstNo: null,
 };

So, when the API will get invoked and the response is received, gstNo props will be updated in the redux store.

this.state.gstNo will be updated inside the UNSAFE_componentWillReceiveProps(), when this.props.gstNo changes. Like Below:

if (this.props.gstNo !== nextprops.gstNo) {
  let gstNo;
  if (nextprops.gstNo) {
      gstNo = nextprops.gstNo;
  } 
  else {
      gstNo = null;
  }

 this.setState({
   gstNo: gstNo,
  });

And to assign this.state.gstNo value to formik, I simply wrote this:

<FormGroup className="col-6">
    <Field
        className="form-control"
        name="GstNo"
        disabled={this.state.gstNo}
        type="text"
        maxLength="15"
        value={
            (values.GstNo = this
                .state.gstNo
                ? this.state.gstNo
                : values.GstNo)
        }
    />
    <Label className="impo_label">
        GST No
    </Label>
</FormGroup>

So as soon as this.state.gstNo would be having some value, it would be reflected in formik form's text field and the textbox will be disabled.

score:0

It's better to use setFieldValue, When the API gets some value or any props/dependency value changes, you can use useEffect to handle it, For Example: I'm getting setFieldValue function as a prop from parent component.

useEffect(() => {
    if (
        values.parentCategoryId &&
        !categories?.data?.find(category => category.id === values.categoryId)
            ?.hasFurnishingStatus
    ) {
        setFieldValue('furnishingStatus', '');
    }
}, [values?.categoryId]);

Here the furnishingStatus is the name of the field for which I'm setting the value.

<Field name="furnishingStatus" component={RadioGroup} row>{...}</Field>

score:0

you can use this method

     useEffect(() => {
        // get user and set form fields
        userService.getById(id).then(user => {
        const fields = ['title', 'firstName', 'lastName', 'email', 'role'];
        fields.forEach(field => setFieldValue(field, user[field], false));
        setUser(user);
        });
    }, []);

score:1

When data comes from api. You can just easy change value of field like this:

setFieldValue('GstNo', valueFromApi)

score:16

You can enable enableReinitialize property of Formik to update the field.

<Formik
   enableReinitialize={true}
   initialValues={...}
>
....

Related Query

More Query from same tag