react-bootstrap-typeahead

Queries with minLength equal to zero


So I am creating this search component based on react-bootstrap-typeahead with multiple sources migrating from old jQuery based typeahead as mentioned in my previous post. One of the sources is a list of previously searched values, queried on React store.

However the current search component has a special case: if nothing is typed on the search bar (i.e. the user focus the input), it displays a list of the previously searched values:

previously searched items with empty input

I have tried replicating that behavior by setting minLength={0} and handling it in the handleSearch function (testing if query === ''), however the function is not called when the input is empty:

type to search

Is it possible to run the handleSearch function with an empty input? Or should I simply do it manually attach an event to the onFocus and display the content manually when the input is empty and hiding it onBlur and when the input is not empty?

Thanks in advance.


Solution

  • So the way I did in the end was, inside of the component (assume that the results that you want to show are received as props.searchHistory, and you want to display them grouped as previousResults):

    const [isEmptySearchInitialized, setIsEmptySearchInitialized] = useState(false);
    
    const setEmptySearchResults = () => {
        const { searchHistory } = props;
        const previousResults = searchHistory;
        const concatenatedPreviousResults = { previousResults };
        setOptions(previousResults);
        setGroupedSearchData(concatenatedPreviousResults);
        setIsEmptySearchInitialized(true);
    };
    
    const handleInputChange = (text, event) => {
        // resets to previously search items when user erases the text input
        if (text === '') {
            setEmptySearchResults();
        }
    };
    
    if (!isEmptySearchInitialized) {
        setEmptySearchResults();
    }
    
    // (...)
    
    return (
        <AsyncTypeahead
            onInputChange={handleInputChange}
            // (...)
        />
    );
    

    Doing so it sets the options with the previousResults, displaying them as initial options when the user clicks on the input, and sets it again when the user erases the search options.

    showing options with empty text