rkit / react-select2-wrapper

Wrapper for Select2
MIT License
163 stars 97 forks source link

Changing data doesn't cause select2 to update #88

Open CWSites opened 5 years ago

CWSites commented 5 years ago

I'm trying to change All to the text of whatever basisList is selected. I am able to correctly update it to Users (ID) using componentWillMount().

My problem is, if I change the basisList that is selected to machines which calls this.updateResolutionText() does not cause select2 to re-render. I can see that my state has been updated correctly, however select2 isn't updating.

What am I missing? I would think that by updating this.state.resolutionOptions that my select2 component would automatically update, thus displaying the new text.

this.state = {
    resolutionOptions: [
        { text: 'All', id: 0, value: 'all' },
        { text: 'Month', id: 1, value: 'Monthly' },
        { text: 'Day', id: 2, value: 'day' },
        { text: 'Day-Hour', id: 3, value: 'Day-Hour' },
        { text: 'Hourly (0-23)', id: 4, value: 'hourly' },
        { text: 'Day of Week', id: 5, value: 'dow' }
    ]
}

componentWillMount() {
    this.updateResolutionText()
}

componentDidUpdate() {
    // this returns correctly {text: 'Machines', id: 0, value: 'all'}
    console.log(this.state.resolutionOptions[0]);
}

updateResolutionText() {
    let basisList = [
        {text: 'Users (ID)', id: 0, value: 'users'},
        {text: 'Machines', id: 1, value: 'machines'}
    ];
    let options = [...this.state.resolutionOptions];
    let comparison = 'users';

    if(basisList) {
        for(let i = 0; i < basisList.length; i++) {
            if(basisList[i].value === comparison) {
                options[0].text = basisList[i].text
                break;
            }
        }
    }

    this.setState({ resolutionOptions: options });
}

<Select2 className="form-control"
         ref="resolution"
         data={this.state.resolutionOptions}
         defaultValue={0}/>