Skip to content

Commit f823b02

Browse files
committed
Refactor search form to use nuqs for query state
Replaces manual search query handling with nuqs's useQueryState for improved URL query management in the search form. Adds nuqs dependency to package.json.
1 parent df59314 commit f823b02

File tree

2 files changed

+16
-11
lines changed

2 files changed

+16
-11
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
"next-cloudinary": "^6.16.0",
3939
"next-seo": "^6.8.0",
4040
"nextjs-progressbar": "^0.0.16",
41+
"nuqs": "^2.7.2",
4142
"postcss": "^8.5.6",
4243
"postgres": "^3.4.7",
4344
"prettier": "^3.6.2",

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)