Estoy tratando de crear una aplicación donde el usuario pueda buscar varios elementos. ahora mi pregunta es ¿cómo puedo enviar de manera eficiente una solicitud de búsqueda de usuario al servidor?
ejemplo, el usuario escribirá algo (digamos 15 caracteres). Por cada 1 carácter, envía una solicitud al servidor (usando axios). ahora está escribiendo tan rápido, en 3 segundos ha enviado 15 solicitudes al servidor... debido a 15 solicitudes paralelas, mi aplicación muestra el resultado real últimamente (o en algún momento falla). por favor, ayúdenme, ¿cómo puedo resolverlo? Estoy usando reaccionar nativo con axios.
ejemplo:
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}); } }Puede usar setTimeout para manejar ese caso
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 } }Si quieres tener una comprensión más profunda, puedes leer este artículo.
https://www.freecodecamp.org/news/javascript-debounce-example/
Creo que puedes dividir el problema en dos pasos.