-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch-input.tsx
57 lines (48 loc) · 1.69 KB
/
search-input.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"use client";
import { Search } from "lucide-react";
import { Input } from "@/components/ui/input";
import { useRouter, useSearchParams } from "next/navigation";
import { ChangeEventHandler, useEffect, useState } from "react";
import { useDebounce } from "@/hooks/use-debounce";
import qs from "query-string";
export const SearchInput = () => {
const router = useRouter();
const searchParams = useSearchParams();
// TODO: for fetching the category id for querries controlling the current loaded category
// currently useless
const categoryId = searchParams.get("categoryId");
const name = searchParams.get("name");
const [value, setValue] = useState(name || "");
const debounceValue = useDebounce<string>(value, 500);
// changes the url to add the category id in url only after waiting 500ms after the user's last keystroke.
// this enables not wasting time for changing the url after each keystroke and
// only changes when it realizes the user has finished typing in the search bar
const onChange: ChangeEventHandler<HTMLInputElement> = (event) => {
setValue(event.target.value);
};
useEffect(() => {
const query = {
name: debounceValue,
categoryId: categoryId,
};
const url = qs.stringifyUrl(
{
url: window.location.href,
query,
},
{ skipEmptyString: true, skipNull: true }
);
router.push(url);
}, [debounceValue, router, categoryId]);
return (
<div className="relative">
<Search className="absolute h-4 w-4 top-3 left-4 text-muted-foreground" />
<Input
placeholder="Search..."
onChange={onChange}
value={value}
className="pl-10 bg-primary/10"
/>
</div>
);
};