As the title states, I'd like to set an initial/default value from the response that gets returned from the loadOptions promise in Select.Async. Am I missing something or is this possible through the API?
Ok, I actually found a solution to this. I'm binding the keyword this to the props.loadOptions, and in my custom loadOptions function, I can call this.setState which captures the context of my custom FormSelect component. What do you think?
Internal Select component setup:
var SelectComponent = Select;
if (has(props, 'loadOptions')) {
SelectComponent = Select.Async;
props.loadOptions = props.loadOptions.bind(this);
}
return (
<SelectComponent
ref='select'
{...props}
onChange={this.handleChange}
value={this.state.value || value}
/>
);
Custom Select component used in parent component:
<FormSelect
loadOptions={function() {
return axios.get('/my-endpoint')
.then((response)=>{
return response.data.data;
})
.then((data)=>{
var options = data.map((obj)=>{
return {
value: obj.id,
label: obj.name,
};
});
this.setState({
value: options[0]
});
return {
options
};
});
}}
This worked for me! I think it'd be cleaner to allow for setting a property on the option that designated it as the default, but this seems to work well.
Here's my hack:
<Select
loadOptions={(() => {
let initialLoad = true;
return input => {
if(initialLoad) {
initialLoad = false;
return Promise.resolve({
options: [formData.s2customer],
complete: false,
});
}
if(input.length < 2) {
return Promise.resolve({
options: [],
complete: false,
});
}
return ajax(customerSelect2Url, {
method: 'GET',
queryParams: {term: input}
}).then(res => {
if(!res.ok) {
throw new Error("Error fetching customer data");
}
//console.log('res.data',res.data);
return {
options: res.data.results,
complete: !res.data.more,
}
})
}
})()}
/>
The key is to set this dummy initialLoad variable so you can return some pre-fetched data on the first run.
Hello -
In an effort to sustain the react-select project going forward, we're closing old issues / pull requests.
We understand this might be inconvenient but in the best interest of supporting the broader community we have to direct our limited efforts to maintain the latest version.
If you feel this issue / pull request is still relevant and you'd like us to review it, please leave a comment and we'll do our best to get back to you.
Most helpful comment
Ok, I actually found a solution to this. I'm binding the keyword
thisto the props.loadOptions, and in my custom loadOptions function, I can callthis.setStatewhich captures the context of my customFormSelectcomponent. What do you think?Internal Select component setup:
Custom Select component used in parent component: