Nextjs 14 App Router fetch data as the searchParams change

I use App router in Nextjs 14. I'm having a problem fetching my data from page component as I change the searchParams in client component using params.set and params.delete. It is causing Hydration error. Can somebody guide me?
1 Reply
Stepan
Stepan10mo ago
the way I did it in one of my apps was using router.push for your page using params make sure you're taking searchParams from the page props like this:
interface PageProps {
searchParams: Record<string, string | undefined>;
}

export default async function Page({ searchParams }: PageProps) {
// page logic here
}
interface PageProps {
searchParams: Record<string, string | undefined>;
}

export default async function Page({ searchParams }: PageProps) {
// page logic here
}
and in your client component:
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();

const setParam = (param: string, value: string) => {
const current = new URLSearchParams(
Array.from(searchParams.entries()),
);

current.set(param, value); // or current.delete(param)

// cast to string
const search = current.toString();
const query = search ? `?${search}` : "";

router.push(`${pathname}${query}`);
}
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();

const setParam = (param: string, value: string) => {
const current = new URLSearchParams(
Array.from(searchParams.entries()),
);

current.set(param, value); // or current.delete(param)

// cast to string
const search = current.toString();
const query = search ? `?${search}` : "";

router.push(`${pathname}${query}`);
}
not sure if this is the correct way to work with searchParams in app router but it worked fine for me
Want results from more Discord servers?
Add your server