I am trying to build an application where user can search for various items. now my question is how can I send efficiently user search request to the server ?
example , user will type something (say 15 characters). For every 1 character he is sending one request to the server (using axios). now he is typing so fast, within 3 seconds he has sent 15 request to the server.. due to 15 parallel requests, my app is showing the actual result lately (or sometime failing). please help me how can i solve it.. I am using react native with axios.
example:
async searchLocation(text) {
if (text.length > 3) {
this.setState({searching: true, searchResultWindow: true});
var getSearchResult = await searchPlace(text); /// Here I am making axios call to our server
this.setState({searching: false, searchResults: getSearchResult.message});
}
}
CodePudding user response:
You can use setTimeout
to handle that case
let timer //the global variable to track the timer
async searchLocation(text) {
if (text.length > 3) {
//remove the API trigger within 3 seconds
clearTimeout(timer)
//assign new timer for the API call
timer = setTimeout(() => {
this.setState({searching: true, searchResultWindow: true});
var getSearchResult = await searchPlace(text); /// Here I am making axios call to our server
this.setState({searching: false, searchResults: getSearchResult.message});
}, 3000) //the API only triggers once users stop typing after 3 seconds
}
}
If you want to have deeper understanding, you can read this article
https://www.freecodecamp.org/news/javascript-debounce-example/
CodePudding user response:
I think you can divide the issue into two steps
- At the first you must find a word that the user wants to type for search (not result of search) in this step, you can just use a dictionary
- The second step is finding user search results after pressing Enter key or Click to the search button