Celebrating 80th Independence Day of India• Jai Hind •Bharat Mata Ki Jai• Jai Hind •Long Live India• Jai Hind •Jai Hind• Jai Hind •

LLD Auto Complete Searchbar

Ashutosh Anand Tiwari
By Ashutosh Anand TiwariPublished Feb 25, 2025 · 2 min read

Live Deployed Link

Github Code Link

import { useEffect, useRef, useState } from 'react';
let timeoutId;
const AutoComplete = () => {
  const [search, setSearch] = useState('');
  const [list, setList] = useState([]);
  const [isVisible, setIsVisible] = useState(false);

  const fetchData = (query) => {
    console.log('get called', query);
    if (!query) return;
    console.log(query);
    fetch(`https://www.google.com/complete/search?client=firefox&q=${query}`)
      .then((res) => res.json())
      .then((data) => {
        console.log(data[1]);
        setIsVisible(true);
        setList(data[1]);
      });
  };
  console.log('New');

  const debounce = (func, delay) => {
    if (timeoutId) clearTimeout(timeoutId);

    // if (timeoutId) clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      func(search);
    }, delay);
  };

  // const debouncedFetchData = debounce(fetchData, 2000);

  useEffect(() => {
    debounce(fetchData, 400);
  }, [search]);
  return (
    <div>
      <h1 className='mb-2 text-2xl font-bold'>Auto Complete</h1>

      <input
        type='text'
        value={search}
        onFocus={() => setIsVisible(true)}
        onBlur={() => setIsVisible(false)}
        onChange={(e) => {
          console.log(e.target.value);
          setSearch(e.target.value);
        }}
        className='w-full rounded-md border p-2'
        placeholder='Search...'
      />
      {isVisible && (
        <ul className='mt-2 flex flex-col justify-center rounded-md border p-1 shadow-md'>
  
            <>
              {list?.map((item, index) => (
                <li key={index} className='cursor-pointer p-2 hover:bg-gray-200'>
                  {item}
                </li>
              ))}

              {list?.length == 0 && <li className='mt-4 opacity-30'>No Results</li>}
            </>
     
        </ul>
      )}
    </div>
  );
};

export default AutoComplete;

Continue Exploring

Profile

Ashutosh Anand Tiwari

Follow

Writer & curator of this digital garden — open notes for learners worldwide.

🌱 Planted and watering by :

🙏 धन्यवाद ! 🙏

tiranga
Request a Topic

Want me to write notes on a course?

Tell me the course, book, or research topic you want covered. If it helps learners, I'll consider adding structured digital notes for it in the garden.

Collaborate

Have a notes collection to feature here?

Do you have open notes you want featured in this digital garden? Let me know — we can collaborate and publish them for learners worldwide.