Edy Hartono
Edy Hartono

Reputation: 1

react-select using onInputChange with ajax call

i'm using react-select and trying to update the options array dynamically with onInputChange props via an ajax call, the problem here is text input got reseted everytime user press a key because of DOM update. My code is following

render: function() {
    var valueField;
    if(this.props.editAble){

        valueField =  <td className="col-md-12">
                                        <Select ref="child" options={options} onInputChange={this._getUsers}/>
                                    </td>;
    }
    else{
        valueField = <td>{this.props.value}</td>;
    }

    return (
        <tr>
            <td className="info-key">{this.props.param}</td>
            <td className="sep">:</td>
            {valueField}
        </tr>
    );
},
_getUsers: function(input){
    UserActions.search(input);
    var optionsDirty = UserStore.getUsers();
    options = [];
    //debugger;
    optionsDirty.map(function(option){
        options.push({value:option.id, label:option.firstName+' '+option.lastName});
    });
    this.forceUpdate();
}

what i try to get here is something like stackoverflow tags input (similar but not exactly same)

Upvotes: 0

Views: 2259

Answers (1)

Damien Leroux
Damien Leroux

Reputation: 11693

Because of this.forceUpdate();, your form is erased and redisplayed. To have your select field keep the current value, you must save the input from _getUsers: function(input) in your component and then give it to <Select> through the prop value.

Beside, there is no need to call forceUpdate if you call setState: it will refresh your component as well. And you should put your options in the state in that case.

Do more something like:

render: function() {
    var valueField;
    if(this.props.editAble){
        valueField =  <td className="col-md-12">
                                        <Select ref="child" options={this.state.options} onInputChange={this._getUsers} value={this.state.value}/>
                                    </td>;
    }
    else{
        valueField = <td>{this.props.value}</td>;
    }

    return (
        <tr>
            <td className="info-key">{this.props.param}</td>
            <td className="sep">:</td>
            {valueField}
        </tr>
    );
},
_getUsers: function(input){
    UserActions.search(input);
    var optionsDirty = UserStore.getUsers();
    options = [];
    //debugger;
    optionsDirty.map(function(option){
        options.push({value:option.id, label:option.firstName+' '+option.lastName});
    });

    //update component with new options and the current value
    this.setState({
        options:options,
        value:input
    });
}

Upvotes: 1

Related Questions