skip to Main Content

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


  1. Use the debounce function from npm packages which will make a delay while the user types before making a request to the API.

    const debounceDelay = 300;
    
    const handleDebouncedChange = debounce((event) => {
        console.log('Debounced value:', event.target.value);
    }, debounceDelay);
    
    <input
        type="text"
        onChange={(e) => handleDebouncedChange(e)}
    />
    
    Login or Signup to reply.
  2. 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.

    import React, { useState, useEffect } from 'react';
    
    const DebouncedInput = () => {
      const [inputValue, setInputValue] = useState('');
      const [debouncedValue, setDebouncedValue] = useState('');
    
      useEffect(() => {
        const delayDebounceFn = setTimeout(() => {
          setDebouncedValue(inputValue);
        }, 500);
    
        return () => clearTimeout(delayDebounceFn);
      }, [inputValue]);
    
      const handleChange = (e) => {
        setInputValue(e.target.value);
      };
    
      return (
        <div>
          <input
            type="text"
            value={inputValue}
            onChange={handleChange}
            placeholder="Type something..."
          />
          <p>Debounced value: {debouncedValue}</p>
        </div>
      );
    };
    
    export default DebouncedInput;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search