Chapter 11 - Implement debouncing

This commit is contained in:
2024-01-03 08:46:41 +01:00
parent 500928c719
commit 4f2ab25f16
3 changed files with 18 additions and 2 deletions

View File

@@ -2,12 +2,15 @@
import { MagnifyingGlassIcon } from '@heroicons/react/24/outline';
import {usePathname, useRouter, useSearchParams} from "next/navigation";
import { useDebouncedCallback } from 'use-debounce';
export default function Search({ placeholder }: { placeholder: string }) {
const searchParams = useSearchParams();
const pathname = usePathname();
const { replace } = useRouter();
function handleSearch(term: string) {
const handleSearch = useDebouncedCallback((term) => {
console.log(`Searching... ${term}`);
const params = new URLSearchParams(searchParams);
if (term) {
params.set('query', term);
@@ -16,7 +19,7 @@ export default function Search({ placeholder }: { placeholder: string }) {
}
replace(`${pathname}?${params.toString()}`);
}
}, 300)
return (
<div className="relative flex flex-1 flex-shrink-0">
<label htmlFor="search" className="sr-only">