Skip to content

Commit 3a5c719

Browse files
authored
Refactor SearchParams to nuqs searchState
1 parent 3065bee commit 3a5c719

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

src/app/(public)/_components/search-form.tsx

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,29 @@
11
'use client';
22

3-
import { usePathname, useSearchParams, useRouter } from 'next/navigation';
3+
import { usePathname } from 'next/navigation';
44
import { useForm } from 'react-hook-form';
55
import { GoX } from 'react-icons/go';
6+
import { useQueryState } from 'nuqs';
67

78
interface FormValues {
89
searchQuery: string;
910
}
1011

1112
export function SearchForm() {
12-
const router = useRouter();
1313
const pathname = usePathname();
14-
const searchParams = useSearchParams();
14+
const [searchQuery, setSearchQuery] = useQueryState('q', {
15+
defaultValue: '',
16+
parse: (value: string) => value,
17+
serialize: (value: string) => value || ''
18+
});
1519

1620
const { register, handleSubmit, reset, watch } = useForm<FormValues>({
1721
defaultValues: {
18-
searchQuery: searchParams.get('q') as string
22+
searchQuery: searchQuery
1923
}
2024
});
2125

22-
const searchQuery = watch('searchQuery');
26+
const queryValue = watch('searchQuery');
2327

2428
if (!pathname.startsWith('/repos')) {
2529
return null;
@@ -28,12 +32,9 @@ export function SearchForm() {
2832
function onSubmit({ searchQuery }: FormValues) {
2933
if (!pathname.startsWith('/repos')) return;
3034

31-
const reposPathname = pathname as `/repos/${string}`;
3235
const trimmedQuery = searchQuery.trim();
3336
if (trimmedQuery !== '') {
34-
const sp = new URLSearchParams(searchParams);
35-
sp.set('q', trimmedQuery);
36-
router.push(`${reposPathname}?${sp.toString()}`);
37+
void setSearchQuery(trimmedQuery);
3738
}
3839
}
3940

@@ -47,11 +48,14 @@ export function SearchForm() {
4748
type="text"
4849
{...register('searchQuery', { required: true })}
4950
/>
50-
{searchQuery && searchQuery.trim() !== '' && (
51+
{queryValue && queryValue.trim() !== '' && (
5152
<button
5253
className="absolute top-0 right-0 rounded-l-none btn btn-ghost btn-sm"
5354
type="button"
54-
onClick={() => reset()}
55+
onClick={() => {
56+
reset();
57+
void setSearchQuery(null);
58+
}}
5559
>
5660
<GoX color="white" />
5761
</button>

0 commit comments

Comments
 (0)