sickdyd / react-search-autocomplete

A search box that filters the provided array of objects
https://sickdyd.github.io/react-search-autocomplete
MIT License
220 stars 84 forks source link

Updating `items` prop causes search list to pop up (after item selected) #13

Closed jonathanni closed 3 years ago

jonathanni commented 3 years ago

I'm not sure this is supposed to happen. Suppose I had a simple component:

import React from 'react';
import { ReactSearchAutocomplete } from 'react-search-autocomplete';

import './App.css';

const AssetSearch = ({ setAssetCallback }) => {
    const [assetList, setAssetList] = React.useState([])

    React.useEffect(() => {
        const refreshData = () => {
            const data = [{
                id: 0,
                name: "babooka",
            }, {
                id: 3,
                name: "melon",
            }, {
                id: 5,
                name: "bazoonka",
            }, {
                id: 6,
                name: "pop",
            }];
            setAssetList(data);
        };
        refreshData();
        setInterval(refreshData, 10 * 1000);
    }, []);

    return <ReactSearchAutocomplete
        items={assetList} onSelect={item =>
            setAssetCallback(item.name)}
        fuseOptions={{
            shouldSort: true,
            threshold: 0.6,
            location: 0,
            distance: 100,
            maxPatternLength: 32,
            minMatchCharLength: 1,
            keys: [
                "name",
                "id",
            ],
        }}
        placeholder="ID/name" />;
};

const App = () => {
    const [asset, setAsset] = React.useState(null);

    return (
        <div className="App">
            <AssetSearch setAssetCallback={setAsset} />
            Asset selected: {!asset ? "none" : asset}
        </div>
    );
}

export default App;

The first time items is set on the component, the search suggestions don't pop up unless we focus on the component, which is expected behavior. But once we select an item and wait for 10 seconds, the callback to refresh the data fires, items is re-set, and the search suggestions pop up again.

Is there any way to disable this behavior?

Thanks

sickdyd commented 3 years ago

Hallo @jonathanni! Thank you for reporting this issue. I fixed the issue in the release 5.0.5. Check out the codesandbox below. I also made it so that the values are different at each update, so that you can see that the search results are updated as soon as items are updated.

https://codesandbox.io/s/runtime-pond-w77zk?file=/src/App.js

jonathanni commented 3 years ago

This looks great, updated the package on my end and we don't have issues anymore. Thank you for resolving this issue!