Rushi M Thakker
Rushi M Thakker

Reputation: 679

Antd Select restore/keep old value and not update with new selected option

I have an antd form which has a select component as form item. Something like this:

        <Form.Item label='Client Name'>
        {
          getFieldDecorator('clientId', {
            rules: [{
              required: true,
              message: 'Please select client!',
            }],
            initialValue: this.state.clientId
          })(
            <Select
              showSearch
              loading={this.props.isClientLoading}
              optionFilterProp='title'
              style={formItemStyle}
              placeholder='Select Client'
              onChange={this.handleClientChange}
            >
              {this.props.clientOptions}
            </Select>
          )
        }

I am maintaining a state for clientId. Whenever user selects an option from select dropdown, I update the state value in method handleClientChange. But, in one condition, I don't want to update the state value and in that case dropdown selection should also not change. But the thing is select calls handleClientChange method and then updates the dropdown field. My handleClientChange code looks something like this:

  handleClientChange = async (selectedClientId: any) => {
    if (this.state.isSomethingChanged) {
      debugger;
/*       setTimeout(() => {
        this.props.form.setFieldsValue({ clientId: this.state.clientId});
      }, 100); */
      this.props.form.setFieldsValue({ clientId: this.state.clientId});

As you can see, I tried to update props form value but it updates for a fraction of second and then select internally fires the new value and changes it.

As you can also see, I tried a work around of setting a timeout and it works but that is a very unpleasant UX. Can someone help me in restoring the old value of dropdown?

P.S. : I tried setting value prop of select component but that doesn't work when it is wrapped in getFieldDecorator. Antd takes care of making it a controlled component.

Upvotes: 0

Views: 2095

Answers (1)

Vrunda Thacker
Vrunda Thacker

Reputation: 118

If you do not want a particular option to be selected:

  1. Do not create an option for it
  2. Make is disabled so that it cannot be selected

Upvotes: 1

Related Questions