Next.js Discord

Discord Forum

Debounce from Tutorial not working

Answered
Barbary Lion posted this in #help-forum
Open in Discord
Barbary LionOP
I'm following the tutorial, and at the "Adding Search and Pagination" section.

At the very end, we have a debounce technique to debounce the request to the server but it doesn't seem to be working... Here is the code used for my search.tsx component:

'use client';

import { MagnifyingGlassIcon } from '@heroicons/react/24/outline';
import { usePathname, useSearchParams, useRouter } from 'next/navigation';
import { useDebouncedCallback } from 'use-debounce';

export default function Search({ placeholder }: { placeholder: string }) {
  const searchParams = useSearchParams();
  const pathname = usePathname();
  const { replace } = useRouter();

  const handleSearch = useDebouncedCallback((term) => {
    console.log(`Searching... ${term}`);

    const params = new URLSearchParams(searchParams);
    if (term) {
      params.set('query', term);
    } else {
      params.delete('query');
    }
    replace(`${pathname}?${params.toString()}`);
  }, 300);

  return (
    <div className="relative flex flex-1 flex-shrink-0">
      <label htmlFor="search" className="sr-only">
        Search
      </label>
      <input
        className="peer block w-full rounded-md border border-gray-200 py-[9px] pl-10 text-sm outline-2 placeholder:text-gray-500"
        placeholder={placeholder}
        onChange={(e) => {
          handleSearch(e.target.value);
        }}
        defaultValue={searchParams.get('query')?.toString()}
      />
      <MagnifyingGlassIcon className="absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500 peer-focus:text-gray-900" />
    </div>
  );
}


I even tried changing the debounce time to 3000 and its still updating my search params and querying after every input. Have I done something wrong? Maybe this is a bug with the use-debounce library?
Answered by Barbary Lion
Not sure what happened but its working now! Made a change to the page and magically started working lol
View full answer

3 Replies

Barbary LionOP
Barbary LionOP
Not sure what happened but its working now! Made a change to the page and magically started working lol
Answer
Haha, it… sometimes does happen. Glad it worked