Pratik
Pratik

Reputation: 1541

loadOptions getting called for same string which was searched earlier and cacheOptions is enabled

I am trying to use AsyncSelect from react-select library.

I have enabled cacheOptions option.

Using below mentioned steps I am seeing an issue with loadOptions

  1. Search for a string test
  2. List of options gets displayed
  3. Clear the input field
  4. Enter same string again test
  5. Immediately displays same list of options
  6. loadOptions fires an API with search input tes
  7. Clear the input field
  8. Enter same string again test
  9. Immediately displays same list of options
  10. loadOptions fires API with search input te.

I am not sure why loadOptions getting fired in this scenario if I am entering the same search string.

Here is the AsyncSelect

<AsyncSelect
  classNamePrefix="select-item"
  onChange={ onOptionSelect }
  getOptionValue={ item => item.id }
  placeholder="Search by Item"
  formatOptionLabel={ company => <CompanyWithIcon Item={ Item } /> }
  loadOptions={ loadOptions }
  styles={ customStyles }
  isSearchable
  cacheOptions
  isClearable
/>

Here is the loadOptions function

const loadOptions = inputValue => searchItem(inputValue);

Can anybody please help?

Upvotes: 0

Views: 356

Answers (1)

hshob_19
hshob_19

Reputation: 11

I think it is happening because you are not using a callback or a promise for loadOptions. The loadOptions should return a promise.

Reference doc -> https://react-select.com/props#async-props says:

loadOptions: Function that returns a promise, which is the set of options to be used once the promise resolves.

It should be like below:

const loadOptions = (inputValue, callback) => {
  setTimeout(() => {
    callback(searchItem(inputValue));
  }, 1000);
};

Upvotes: 0

Related Questions