Okay so I've implemented a searchable multi-selectable dropdown from react-semantic-ui. (https://react.semantic-ui.com/modules/dropdown/)
It normally works frontend, so you can enter search queries in the input field and the results are filtered realtime.
I want to implement backend searches, which are done using an axios call with a searchQuery variable. The problem is that everytime a key is pressed the onSearchChange is fired to make the new search, which rerenders the dropdown thus closing the drowdown and clearing the query.
The returned data is an array that matches the search with that one pressed key, but this is not rendered in the new dropdown options and on reopening the dropbox the searchquery also has been cleared.
I can't really figure out how to make a backend search without a state changing, which then causes a rerender and clears everything. Any suggestions as how to go about this ?
const ParentComponent = () => {
const [options, setOptions] = useState()
const [searchString, setSearchString] = useState('')
useEffect(() => {
const fetchOptions = async (searchString) => {
// getOptions is just an async axios.get, which returns an options array based on the search criteria
const response = await getOptions(searchString)
setOptions(response)
}
fetchOptions(searchString)
}, [searchString])
const handleSearchChange = (e, search) => {
setSearchString(() => search.searchQuery)
}
return(
<DropDown
onSearchChange={handleSearchChange}
searchQuery={searchString}
options={options}
/>
)}
The following should work, I set the search property to a function: search={() => options}
and resolve filterCountries only when it was the last user input.
In the example when search is one character long it will take 2 seconds to resolve but if it's not it will take 500 milliseconds. So if I type a
and then al
there are 2 promises, the promise al
resolves quickly and sets the options but later the promise a
resolves and would overwrite the options if I would not use last
.
I also added debounce and group in the code, the group will cache results until page reloads, you can cache any kind of way by replacing the createCache logic.