react-select async creatable does not recommend

Viewed 1926

I'm trying to use AsyncCreatableSelect with example data :

[
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' }
]

My code looks like this :

const fetchData = () => {
    return new Promise(resolve=>{
        resolve([
            { value: 'chocolate', label: 'Chocolate' },
            { value: 'strawberry', label: 'Strawberry' },
            { value: 'vanilla', label: 'Vanilla' }
        ])
    })
}

const component = () => {
    return(
            <AsyncCreatableSelect
                cacheOptions
                defaultOptions
                loadOptions={fetchGameList}
            />
    );
}

And the problem is that, the data is correctly loaded but when I type, I don't get any recommendation compared to the examples on the website :

Example

Whatever I type in the input, the result is always the same.

3 Answers

On the documentation you linked, it includes the "filterColors" function. You need to implement a similar or equivalent function, and wrap the return value of the "loadOptions" function in it, the same way they do.

import React, { Component } from 'react';

import AsyncCreatableSelect from 'react-select/async-creatable';
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<*, State> {
  render() {
    return (
      <AsyncCreatableSelect
        cacheOptions
        defaultOptions
        loadOptions={promiseOptions}
      />
    );
  }
}

Refer to "promiseOptions" above, which is the function used for "loadOptions".The inputValue returned is wrapped in the "filterColors" function, which does the sorting.

It would be best if your fetchGameList already returned the sorted list. Your backend would do the sorting.

It's better to use something like useMemo or useCallback and in that list or return add array which you need to present.

You can type

const data = useMemo(() => { ...code... }, [deps])

In ...code... you can type your code but in deps you can watch some variable and once when deps is changed your useMemo will be triggered again...

Related