From 6908cee0c5610e7aedb4a1dc0542207fdf29459f Mon Sep 17 00:00:00 2001 From: Michael Zetterberg Date: Tue, 25 Feb 2025 13:50:45 +0100 Subject: [PATCH] fix: search params passed to Link overrides current search params This changes the behavior of Link prop `keepSearchParams`. Previously it got implicitly merged. Now, any search params in the given `href` prop to Link will override any current search params available on the current page. Handle the merging use case (if there is any) in the components that passes the href to render Link. --- components/TempDesignSystem/Link/index.tsx | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/components/TempDesignSystem/Link/index.tsx b/components/TempDesignSystem/Link/index.tsx index c641eff90..931b4594c 100644 --- a/components/TempDesignSystem/Link/index.tsx +++ b/components/TempDesignSystem/Link/index.tsx @@ -26,7 +26,10 @@ export default function Link({ trackingParams, onClick, /** - * Decides if the link should include the current search params in the URL + * Decides if the link should include the current search params in the URL. + * If the given href also contains search params, they take precedence and + * override any current search params. If you need to merge them, handle that + * in your component that passes the href here. */ keepSearchParams, appendToCurrentPath, @@ -57,8 +60,17 @@ export default function Link({ } if (keepSearchParams && searchParams.size) { - const delimiter = newPath.includes("?") ? "&" : "?" - return `${newPath}${delimiter}${searchParams}` + if (newPath.includes("?")) { + const newPathParts = newPath.split("?") + const newSearchParams = new URLSearchParams(newPathParts[1]) + searchParams.forEach((v, k) => { + if (!newSearchParams.has(k)) { + newSearchParams.set(k, v) + } + }) + return `${newPathParts[0]}?${newSearchParams}` + } + return `${newPath}?${searchParams}` } return newPath