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.
This commit is contained in:
Michael Zetterberg
2025-02-25 13:50:45 +01:00
parent bc50dcf286
commit 6908cee0c5

View File

@@ -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