Need help with searchParams filter (delete param)
Unanswered
Brown bear posted this in #help-forum
Brown bearOP
I built a simple filter functionality where I pass the search param type to my get data function (it fetches the data). Everything works perfect when I choose a type but when I choose the "All Types" option, the search param is removed from the url but the Page server component is not re-rendered (and the getData() function does not re-render to get all the data). Does anyone know how to fix this?
Here is my code:
Here is my code:
// Page /example
export default async function Page({ searchParams }) {
const type = searchParams?.type || '';
const data = await getData(type);
return (
<Fragment>
<Filter />
<p>Content here</p>
</Fragment>
);
}
// Filter component
'use client';
import { useSearchParams, usePathname, useRouter } from 'next/navigation';
export default function Filter() {
const searchParams = useSearchParams();
const pathname = usePathname();
const router = useRouter();
const handleChange = (event) => {
const value = event.target.value;
const params = new URLSearchParams(searchParams);
if (value) {
params.set('type', value);
} else {
params.delete('type');
}
router.replace(`${pathname}?${params.toString()}`);
};
return (
<select
name="type"
defaultValue={searchParams.get('type')?.toString()}
onChange={handleChange}
>
<option value="">All Types</option>
<option value="Type One">Type One</option>
<option value="Type Two">Type Two</option>
<option value="Type Three">Type Three</option>
<option value="Type Four">Type Four</option>
</select>
);
}