How to set value of AsyncSelect outside of the component?
See original GitHub issueI have read all the documentation of AsyncSelect and Select but I didn’t read anything regarding this matter. The problem arose after upgrading from V1 to V3. In V1, I could set value property (a simple value or string) and this would trigger the async loading procedure which would get the right value object (label and value). But, in V3, you should set value with the whole structure, eg, {label: xxx, value: yyy} in order to show it correctly.
For instance, we have this sample:
import React, { Component } from 'react';
import AsyncSelect from 'react-select/async';
import { colourOptions } from '../data';
type State = {
inputValue: string,
};
const filterColors = (inputValue: string) => {
return colourOptions.filter(i =>
i.label.toLowerCase().includes(inputValue.toLowerCase())
);
};
const promiseOptions = inputValue =>
new Promise(resolve => {
setTimeout(() => {
resolve(filterColors(inputValue));
}, 1000);
});
export default class AsyncMulti extends Component<*, State> {
state = { inputValue: '' };
handleInputChange = (newValue: string) => {
const inputValue = newValue.replace(/\W/g, '');
this.setState({ inputValue });
return inputValue;
};
render() {
return (
<AsyncSelect
isMulti
cacheOptions
defaultOptions
value = {1} // this won't work
value = {{value: 1, label: "black"}}
loadOptions={promiseOptions}
/>
);
}
}
All the logic of loading colors is inside the component. In order to set a value from outside, I would have to (in an external procedure) load the array and search for the value which, I think, would duplicate code unnecessarily.
Is there a way to set a value and this would trigger internal loading procedure in order to search for the correct pair?
Issue Analytics
- State:
- Created 4 years ago
- Comments:13
Top GitHub Comments
This is what works for me:
Yes, this is what I’ve done. But I have to (as you said) change my query (outside of the component) and manually craft a label/value object. The problem with this approach is that I had to duplicate this query (one query to search for the label before creating the component) and the other inside the component to loadOptions. Before this version, I could just set the value and it will trigger loadOptions and make this label/value automatically.