Currently, I am working on integrating a search feature in React Native using axios.
For the search functionality, I am incorporating debounce from lodash to control the number of requests being sent.
However, there is a concern about receiving responses out of order and potentially displaying incorrect search results.
For instance, if a user enters 'Home deco' in the search input field, two requests will be generated - one for 'Home' and the next for 'Home deco' as the search query text.
If the request for 'Home' takes longer to return than the request for 'Home deco', the results displayed would be for 'Home' instead of 'Home deco'.
The ideal scenario would be to display both sets of results sequentially, but if 'Home' response comes after 'Home deco' response, it should be ignored.
Below is an example snippet of code:
function Search (){
const [results, setResults] = useState([]);
const [searchText, setSearchText] = useState('');
useEffect(() => {
getSearchResultsDebounce(searchText);
}, [searchText]);
const getSearchResultsDebounce = useCallback(
_.debounce(searchText => {
getSearchResults(searchText)
}, 1000),
[]
);
function getSearchResults(searchText) {
const urlWithParams = getUrlWithParams(url, searchText);
axios.get(urlWithParams, { headers: config.headers })
.then(response => {
if (response.status === 200 && response.data)
{
setResults(response.data);
} else{
//Handle error
}
})
.catch(error => {
//Handle error
});
}
return (
<View>
<SearchComponent onTextChange={setSearchText}/>
<SearchResults results={results}/>
</View>
)
}
What could be the most effective way to address the aforementioned issue?