react-select icon indicating copy to clipboard operation
react-select copied to clipboard

How to set value of AsyncSelect outside of the component?

Open MarcosCunhaLima opened this issue 7 years ago • 14 comments

I 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?

MarcosCunhaLima avatar Sep 17 '19 19:09 MarcosCunhaLima

Using onInputChange prop with your handleInputChange method will trigger a new loadOptions call with the inputValue returned by handleInputChange.

<AsyncSelect
        isMulti
        cacheOptions
        defaultOptions
        value = {1} // this won't work
        value = {{value: 1, label: "black"}}
        loadOptions={promiseOptions}
        onInputChange={this.handleInputChange}
/>

Xartok avatar Oct 04 '19 08:10 Xartok

Hi @Xartok

The problem is not when user is changing it (after the select has focus and user is typing something) as this is working.

The problem is when I set Value prop externally (first time, when, for instance, I set Value prop from database). This won't trigger onInputChange anymore and, in not doing so, it won't load the array options. In V1, I could set Value prop with a simple string (the key) and it will trigger loadOptions promise and will try to get the correct value/label item. In V3, you should set Value prop with value/label.

MarcosCunhaLima avatar Oct 08 '19 14:10 MarcosCunhaLima

So actually, when you set the value from your database, what is displayed:

  • in the menu when you open it
  • in the value container (where it should contain the value here with the label "black")

Xartok avatar Oct 08 '19 20:10 Xartok

In the menu: nothing (as it expects a pair {value/label} in the Value prop. In the Value container: the value I've set (for instance, in the example, "1")

MarcosCunhaLima avatar Oct 08 '19 20:10 MarcosCunhaLima

Ok, so do you store the label along with the value in the database ? If this is the case you can set the value of the AsyncSelect to the object {label: dbLabel, value: dbValue} (without doing loadOptions('').then(options => options.find(opt => opt.value === dbValue)) as this is supported (it will filter out the option with this value in the menu) and avoid an unnecessarily call to loadOptions. But it requires a modification of your database query...

Xartok avatar Oct 11 '19 21:10 Xartok

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.

MarcosCunhaLima avatar Oct 11 '19 21:10 MarcosCunhaLima

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.

Same here. I have only the value/id (not the entire object, like: { value: '1': label: 'First' }). So I set defaultValue like this: { value: form.fieldId } but I don't have the label (It will be searched by loadOptions).

So I need to load my option before render AsyncSelect and pass value or defaultValue prop

alexandrehpiva avatar Nov 16 '20 22:11 alexandrehpiva

Greetings,

Is this still an issue as it sounds like there is a solution?

This type of behavior would require a controlled input and updating the value once the defaultOptions load.

Here is a working demo: codesandbox

As a note, if you would like to trigger the onChange event, there is a selectOption available in the select ref which I believe triggers the onChange methods.

const AsyncExample = ({ defaultOptionValue, ...props }) => {
  const [value, setValue] = useState();
  const [defaultValue, setDefaultValue] = useState();

  useEffect(() => {
    setValue(defaultValue);
  }, [defaultValue]);

  const loadOptions = (searchKey) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        !defaultValue &&
          setDefaultValue(options.find((o) => o.value === defaultOptionValue));
        const filtered = options.filter((o) => o.label.includes(searchKey));

        resolve(filtered);
      }, 5000);
    });
  };

  const onChange = (option) => setValue(option);

  return (
      <Async
        loadOptions={loadOptions}
        defaultOptions
        value={value}
        onChange={onChange}
      />
   );
};

ebonow avatar Dec 18 '20 19:12 ebonow

In an effort to cleanup stale issues, I will be closing this. Please feel free to reply or create a new issue if there are any concerns or reproducible bugs.

ebonow avatar Jan 08 '21 01:01 ebonow

I am doing a similar thing as @MarcosCunhaLima described, I am prefilling the data from the database (which cannot have all those exactly the same data as {value: "", label: "" }), and actually, I was adding more other properties such as {value: "", label: "", thirdProperties... } which makes me hard to prefill the data if the object format is a must. We can do a filter in simple