I am creating a simple flight search website in React. I want the user to be able to search a destination (i.e. Boston), and as they are typing it in have location suggestions appear that they can then select. For this purpose I am using an autocomplete API, which returns a maximum of 5 location objects depending on the current search.
The problem is that my implementation makes a ton of API calls, which with real users would become expensive quickly. Right now I make a call to the API every time the user inputs a keystroke using the onChange() function in a form input field. Is this the standard for autocomplete APIs, or is there a way to minimize the number of API calls made?
I am currently using a button in order to fetch info after the user has inputted their destination, as the autocomplete API calls are too expensive.
2
Answers
Use the
debounce
function from npm packages which will make a delay while the user types before making a request to the API.Here is another way you can understand how debouncing works, here the state will be set 5 mili seconds late after the user stop typing.