How to disable the loading animation in react-select when there is no input text

I am using AsyncSelect to create a text input, to search the text using a REST api and to display the result in the select list. Every thing is working well but when I first load the page I see the loading animation of AsyncSelect. I tried to prevent that but returning null if there is no text in the input but I still see the animation. Do you have any idea?

    import React, { useState } from 'react';
    import AsyncSelect from 'react-select/async';
    
    const MainBanner = () => {
        const [inputValue, setValue] = useState('');
        const [selectedValue, setSelectedValue] = useState(null);
    
        // handle input change event
        const handleInputChange = value => {
            setValue(value);
        };
    
        // handle selection
        const handleChange = value => {
            setSelectedValue(value);
        }
    
        // load options using API call
        const loadOptions = (inputValue) => {
            if (inputValue.length > 1) {
                return fetch(`http://localhost:3001/search/?name=${inputValue}`).then(res => res.json());
            } else {
                return null;
            }
        };
   return (
   <div className="form-group">
      <AsyncSelect className="form-control"
      cacheOptions
      defaultOptions
      value={selectedValue}
      getOptionLabel={e => e.name}
      getOptionValue={e => e.path}
      loadOptions={loadOptions}
      onInputChange={handleInputChange}
      onChange={handleChange}
      />
 </div>

Answer

You could resolve the load options from a callback, rather than using the promise variant, to return immediately and avoid the initial loading animation.

const loadOptions = async (inputValue, callback) => {
    if (inputValue.length > 1) {
        const data = await fetch(`http://localhost:3001/search/?name=${inputValue}`).then(res => res.json());
        callback(data);
    } else {
        callback(null);
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *