Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-select.Async doesn't load options on onClick

I need a Async react-select, which will loadOptions from backend and users will be able to select multiple options. However when inputValue is already entered and users clicks on select input options is not being loaded. They are loaded only when you type something in.

Example code sandbox

Input value stays the same

EDIT: answer

To reload default options you need to pass defaultOptions to Async select, not just true. This can be done by setting defaultOptions to state in componentDidMount and listening for 'menu-close' action in onInputChange and setting defaultOptions to state there. This will ensure that when the component is mounted the defaultOptions will be there, and when menu is closed, the options will be refetched with new inputValue.

like image 489
Simas.B Avatar asked Oct 19 '18 12:10

Simas.B


People also ask

How do I use React-select Async?

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.

How do I set options in React-select?

To select a default option in React, the selected attribute is used in the option element. In React, though, instead of using the selected attribute, the value prop is used on the root select element. So, you can set a default value by passing the value of the option in the value prop of the select input element.

How do I change the placeholder in React-select?

Set the first option element of the select tag to disabled and give it an empty string value. Initialize the state for the select tag to an empty string.

How does React-select work?

Basic usage of react-select js import React from 'react'; import Select from 'react-select'; ... With those two packages imported, we will be able to have access to the react-select ( <Select />) and also extend the React. Component class. In traditional HTML, the <select> tag houses multiple options and values.


1 Answers

To have react-select autoload content you must provide the defaultOptions prop. If you don't autoload then it won't make your async call until they attempt to filter.

<AsyncSelect loadOptions={myAsyncMethod} defaultOptions />
like image 70
Steve -Cutter- Blades Avatar answered Nov 03 '22 09:11

Steve -Cutter- Blades