Next.js Discord

Discord Forum

searchParams are superimposed

Unanswered
kokoan23 posted this in #help-forum
Open in Discord
I'm writing an application using Next js 14 (ts), at this stage I have problems with searchParams
I have a search component, when I click on the search button I get a redirect: router.push(${routes.category}?page=1&perPage=17&${createQueryString("searchQuery", "pip")}), while there are no problems, but if you are on any other page except routes.category itself in the url which already has the page and perPage parameters, then they will overlap each other and you will get the following url: http://localhost:3001/pages/category? page=1&perPage=17&page=1&perPage=17&searchQuery=pip

How can you avoid this problem?

1 Reply

@kokoan23 I'm writing an application using Next js 14 (ts), at this stage I have problems with searchParams I have a search component, when I click on the search button I get a redirect: router.push(`${routes.category}?page=1&perPage=17&${createQueryString("searchQuery", "pip")}`), while there are no problems, but if you are on any other page except routes.category itself in the url which already has the page and perPage parameters, then they will overlap each other and you will get the following url: http://localhost:3001/pages/category? page=1&perPage=17&page=1&perPage=17&searchQuery=pip How can you avoid this problem?
Turkish Van
You could try it by using router.replace().

Here is a code snippet as example.

const searchParams = useSearchParams();
const pathname = usePathname();
const router = useRouter();

const handleSearch = (term: string) => {
        const params = new URLSearchParams(searchParams);
        if (term) {
            params.set("query", term);
        } else {
            params.delete("query");
        }
        router.replace(`${pathname}?${params.toString()}`);
};