AsyncSelect: how to set an initial value?

8.8k Views Asked by At

I am using AsyncSelect and need to change the value of the component based on outside logic. For instance, I have this simple component:

import { colourOptions } from '../data';

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 WithPromises extends Component {
  render() {
    return (
      <AsyncSelect cacheOptions defaultOptions loadOptions={promiseOptions} />
   );
  }
}

Is there a way to set the initial value of it? I thought of using props but I couldn't figure out how execute onChange event as this would load the options array and set label and value.

2

There are 2 best solutions below

2
Gaspar Zsolt On

Try adding a value like this:

<AsyncSelect
  cacheOptions
  defaultOptions
  value={{ label: 'yellow', value: 2 }}
  loadOptions={promiseOptions} />

it worked for me.

0
Muhammad Umer Shahid On

When changing the value from the menu options and selected item not change or changed happened based on outside logic then just use the state in value={yourState} to set the initial & updated values of AsyncSelect. Selected contain object like value={value:'', label:''}

const formFields = {
        name: '',
        foo:'',
        bar:''
}
const [inputs, setInputs] = useState(formFields);

inputs is my state which i used to set the fields values

value={inputs.name ? { label: inputs.name } : { label: 'Search customer...' }}

I used only label:'Search customer...' to make it look like place holder.

<AsyncSelect
    defaultOptions
    value={inputs.name ? { label: inputs.name } : { label: 'Search customer...' }}
    cacheOptions
    onChange={(e) => handleCustomerSelect(e)}
    loadOptions={customerPromiseOptions}
/>

here is my onChange which is called when item is select from dropdown menu

function handleCustomerSelect(selectedOption) {
    const { value } = selectedOption;
    setInputs({ ...inputs, name:value });
}

You can set your initial value from options as well like this