Stepan
Stepan
TTCTheo's Typesafe Cult
Created by Deimos on 1/18/2024 in #questions
Nextjs 14 App Router fetch data as the searchParams change
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
3 replies