Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load React-select Async with initial options for edit item function when using a search API?

I'm using React-Select's Async Select to implement a dropdown where the user will be able to search through a large amount of data. They will see the employee's name when they're searching and they can select multiple employees.

React-select will get the data by using a search API that I have and will insert the query behind by using this method:

const loadOptions = async () => {
        const res = await fetch(`https://example.com/search_user?value=${query}`);
        const data = await res.json();
        const results = data.Result;

        if (results === 'No result found.') {
            return [];
        }

        return results;
    };

What I want to get is the employee ID and their full name, then post both of these info to an API after the user submitted the form.

All these work perfectly but now I want to implement an edit function where the user can edit the Group Members that have been saved into the DB and created.

So naturally I will need to load the react-select's Async dropdown with the initial options, but I have no idea how to load the initial options when I'm using a search API that only will get a certain list of results after I typed something.

I want something like this when the user clicks on edit, which will show the saved employee's name (could be single or multi options selected) from the DB: enter image description here

Here is the codesandbox for reference but I'm only using a fake API link:

Edit strange-resonance-l631s

Edit:

For @Pitter's reference: enter image description here

Latest update: I tried using the value options as mentioned by Pitter, but somehow the input's options is not changing even when I tried to deselect or clear the options and when I tried to search and select a new option.

Final update Finally I got it working! All I need was to set the value props/component to a state and have a handleChange method for the onChange props/component to change the value's state. It actually works as the same way with the usual react-select's Select.

Below is the code that I've used:

// Creating a state for the selected options
const [selectedOption, setSelectedOption] = useState('')

// To set/load the initial value that is saved for the current item to edit/manage
useEffect(() => {
    // Your code to get the initial values, then set it to the state that you've created
   setSelectedOption(initial)
}, [modalInfo]);

// A handle change method to change the selected value/options
const handleChange = (selectedOption) => {
     setSelectedOption(selectedOption);
};

// Then all you need is the onChange method to use the handleChange and 
// having the value set to the state that you've created
return (
        <AsyncSelect
            onChange={handleChange}
            value={selectedOption}
            loadOptions={loadOptions}
            cacheOptions
            defaultOptions
            isMulti
            components={animatedComponents}
            getOptionLabel={(e) => e.fullname}
            getOptionValue={(e) => e.empId}
            onInputChange={(value) => setQuery(value)}
        />
    );
like image 545
Lance Avatar asked Sep 23 '21 01:09

Lance


People also ask

How do you get selected options in React select?

To fetch the selected value from the select element, you can use the onChange event handler prop. Just like the input or textarea elements, you can use the onChange event handler to get the value from the event object. Now, make this select input element controlled by using the state to pass the value.

How to use React select asynchronously in JSX?

To use this functionality asynchronously, you will have to use AsyncCreatable from react-select: And use it in JSX like this: The rest of your code works the same as from previous example. The only thing that is changed is that we are using AsyncCreatable instead of Select.Async.

What are the different features of react select?

In addition to search and selection, React Select offers other features like multi-select, user-creatable options, and async option loading. HTML <select> supports multiple to allow selecting multiple <option> s.

How do I use async option loading in react?

You can use async option loading to allow users to experience faster initial loading times in your application. This will only populate the component when the user interacts with it. Much like the Creatable component, you will need to import AsyncSelect from react-select/async: import AsyncSelect from 'react-select/async'

How to import react select options in react select Tag?

Now import react select in your file import Select from 'react-select' and call that inside return and then pass selectOptions as options inside select tag. After that refresh your browser and see the changes


Video Answer


1 Answers

I was reading the issues on ReactSelect github and found the solution. You need to pass the object in the "value". Take a look in the example below.

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

Reference: https://github.com/JedWatson/react-select/issues/3761

like image 90
Pitter Avatar answered Oct 18 '22 19:10

Pitter